我有一个脚本,在那里我想找出HTTP请求的状态代码。但是,if
语句永远不会计算为true,我也不明白为什么。
#!/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"
我检查了res
的长度,它是16,我在浏览器的控制台中检查了它,它是15,所以我删除了两端的空格,但是它仍然没有计算为真。
res_trimmed="$(echo "${res}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
还是不起作用。
有什么不对的?任何帮助都是非常感谢的。谢谢。
发布于 2017-11-10 22:28:31
更好的实践实现可能如下所示:
#!/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
发布于 2017-11-10 21:44:02
您的问题是,您正在从命令替换中获得返回中的偏离字符。若要消除,只需匹配有效字符。
GREP='/usr/bin/grep -o'
...
res=$($CURL $CURL_ARGS $url | $GREP 'HTTP/1.1[A-Za-z0-9 ]*')
其他变动
echo "'$res'" # This outputs 'HTTP/1.1 200 OK'
示例使用/输出
$ sh curltest.sh
'HTTP/1.1 200 OK'
15
It worked
https://stackoverflow.com/questions/47231354
复制相似问题