我有一个脚本,我想找出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"
我检查了res
的长度,它是16,我在浏览器的控制台中检查了它,它是15,所以我通过删除两端的空格来修剪它,但它仍然没有评估为真。
res_trimmed="$(echo "${res}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
它仍然没有&# 39;工作。
可能出现什么问题?任何帮助表示赞赏。感谢。
答案 0 :(得分:5)
更好的实践实施可能如下:
#!/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
答案 1 :(得分:2)
您的问题是您从命令替换返回时遇到了流浪字符。要消除,只匹配有效字符,例如
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