当我使用时,ping foo.com
我会得到一个响应,或者ping: unknown host foo.com
我正在使用此脚本来显示自定义响应
status=$(ping -c 1 foo.com 2> /dev/null)
if [[ status -ne '200' ]]; then
echo "site found"
else
echo "site not found"
fi
上面的问题是,如果找到站点,我会得到site found
响应,但是如果不是错误消息,我会得到默认响应ping: unknown host foo.com
declare -A websites
websites=("" "")
function ping_sites(){
if [[ $1 != 'all' ]]; then
status=$(curl -I --stderr /dev/null $1 | head -1 | cut -d' ' -f2)
result=$(ping -c 1 $1 | grep 'bytes from' | cut -d = -f 4 | awk {'print $1'} 2> /dev/null)
if [[ status -ne '200' ]]; then
echo -e "$1 $c_red \t $status FAIL $c_none"
else
echo -e "$1 $c_green \t $status OK $c_none"
fi
else
...
。
ping all
ping foo.com
pingWrap(){
if ping -c 1 "$1" >/dev/null 2>&1; then
echo "site found"
else
echo "site not found"
fi
}
pingWrap foo.com
pingWrap localhost
if ping -c 1 "$1" >/dev/null 2>&1; then
禁止所有输出并测试ping命令的返回状态,该状态为0(成功)或其他值(失败)。
[[ status -ne '200' ]]
接受字符串status
和字符串200
,将每个字符串转换为整数,并测试两个整数的不相等性,这听起来很荒谬。
Shell命令的返回状态保存在该$?
变量中,与HTTP返回代码无关。HTTP在TCP之上运行,而ping甚至不使用TCP。
如果目标站点启动并且使用HTTP,则可以使用以下命令在stdout上获取http状态:
httpStatus(){ curl -s -w %{http_code} "$@" -o /dev/null; }
例如,
httpStatus google.com #200
httpStatus google.com/secret #301
st="`httpStatus "$1"`" &&
case "$st" in
301) echo Moved permanently;;
200) echo Success;;
*) echo Unknown;;
esac
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句