sim*_*meg 0 string bash comparison
我有一个脚本,我想找出HTTP请求的状态代码.但是,该if
陈述从未评估为真,我不明白为什么.
#!/bin/sh
set -e
CURL='/usr/bin/curl'
CURL_ARGS='-o - -I -s'
GREP='/usr/bin/grep'
url="https://stackoverflow.com"
res=$($CURL $CURL_ARGS $url | $GREP "HTTP/1.1")
echo $res # This outputs 'HTTP/1.1 200 OK'
echo ${#res} # This outputs 16, even though it should be 15
if [ "$res" == "HTTP/1.1 200 OK" ]; then # This never evaluates to true
echo "It worked"
exit 1
fi
echo "It did not work"
Run Code Online (Sandbox Code Playgroud)
我检查了res
它的长度,它是16,我在浏览器的控制台中检查它是15,所以我通过删除两端的空格来修剪它但仍然没有评估为真.
res_trimmed="$(echo "${res}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
Run Code Online (Sandbox Code Playgroud)
它仍然无法正常工作.
可能有什么不对?任何帮助表示赞赏.谢谢.
更好的实践实现可能如下所示:
#!/usr/bin/env bash
# ^^^^- ensure that you have bash extensions available, rather than being
# only able to safely use POSIX sh syntax. Similarly, be sure to run
# "bash yourscript", not "sh yourscript".
set -o pipefail # cause a pipeline to fail if any component of it fails
url="https://stackoverflow.com"
# curl -f == --fail => tell curl to fail if the server returns a bad (4xx, 5xx) response
res=$(curl -fsSI "$url" | grep "HTTP/1.1") || exit
res=${res%$'\r'} # remove a trailing carriage return if present on the end of the line
if [ "$res" = "HTTP/1.1 200 OK" ]; then
echo "It worked" >&2
exit 0 # default is the exit status of "echo". Might just pass that through?
fi
echo "It did not work" >&2
exit 1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
108 次 |
最近记录: |