我如何使该脚本捕获其返回的错误类型(500、503、402 等)并将其添加到消息中?
#!/bin/bash
hostlist=(s-example1.us s-example.2.us)
for host in "${hostlist[@]}"; do
if nc -w 2 -z $host 80; then
echo "INFO: ssh on $host responding [Looks Good]"
else
echo "ERROR: ssh on $host not responding[Ooops something went
wrong]"
fi
done
答案1
$?
保存最后运行的命令的状态代码。因此,你可以将 else 块修改为:
else
LAST_STATUS_CODE=$? # save the status code immediately, we don't want to accidentally overwrite it
echo "ERROR: ssh on $host not responding[Ooops something went wrong]"
echo "status code: $LAST_STATUS_CODE"
fi
答案2
您似乎混淆了 SSH、HTTP、退出状态和 HTTP 状态代码。如果您需要 HTTP 状态代码,请使用类似 curl 的命令:
$ curl -LI google.com -s | grep 'HTTP/'
HTTP/1.1 302 Found
HTTP/1.1 200 OK
然后:
#!/bin/bash
hostlist=(s-colin.coverhound.us s-joe.coverhound.us)
for host in "${hostlist[@]}"; do
status=$(curl -LI "$host" -s | grep 'HTTP/')
if [[ $status == *"200 OK"* ]]; then
echo "INFO: HTTP on $host responding [Looks Good]"
else
echo "ERROR: HTTP on $host not responding [Ooops something went wrong]"
printf "%s\n" "$status"
fi
done
因此,hostlist=(google.com/teapot)
我会得到:
ERROR: HTTP on $host not responding [Ooops something went wrong]
HTTP/1.1 301 Moved Permanently
HTTP/1.1 418 I'm a Teapot