所以我有这个脚本 (nettest.sh) 和以下代码:
#!/bin/bash
# Internet Check
linktest="$(ping -c 1 google.com)"
if [[ $linktest != *"not"* ]]; then
echo -e " PASSED "
echo -e " $linktest "
else
echo -e " FAILED "
echo -e " $linktest "
fi
ping不通的结果如下:
ping: google.com: Name or service not known
但这是行不通的。当我有链接时,它会显示正确的消息。但是当链接断开时,它会一直显示 PASSED 消息并显示失败的 ping 消息。
有任何想法吗 ?(使用 Debian/Kali)
您的尝试不起作用的原因是因为在失败时ping
写入,stderr
它没有被 捕获$(...)
,因此linktest
是空的。
stderr
如果将行更改为以下内容,则可以捕获它:
linktest=$(ping -c 1 google.com 2>&1)
但实际上,与其解析输出,不如ping
直接使用 的退出代码,例如:
if ping -c 1 google.com; then
echo " PASSED "
else
echo " FAILED "
fi
您可能还想完全抑制所有输出ping
:
if ping -c 1 google.com &>/dev/null; then
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句