Ping 的 Bash 退出状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18988849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:40:12  来源:igfitidea点击:

Bash Exit Status codes for Ping

bashloopspinghosts

提问by NATHAN C

I am working on a small script that checks if a host is up or down.

我正在编写一个小脚本,用于检查主机是启动还是关闭。

until [ "$STATUS" -eq "0" ]
do
ping -c 1 192.168.0.3
echo The host is down
STATUS=`echo $?`
done

It is supposed to change the status to 0 if it pings a host that is up and exit the until loop. But it doesnt. Even if I echo out the value of $? the value is always zero.

如果它 ping 一个正在运行的主机并退出直到循环,它应该将状态更改为 0。但它没有。即使我回显出$的价值?该值始终为零。

Can anyone help me figure this out please? :)

任何人都可以帮我解决这个问题吗?:)

Thanks in advance

提前致谢

回答by iamauser

You have echo The host is downafter pingcommand. So $?takes the exit status of the echocommand not the pingcommand.

你有echo The host is downping命令。所以$?采用echo命令的退出状态而不是ping命令。

ping -c 1 192.168.0.3
STATUS=$?
if [ $STATUS -ne 0 ]; then
   echo "The host is down"
fi

回答by konsolebox

You placed echo after saving the status that's why you always get 0:

您在保存状态后放置了 echo,这就是为什么您总是得到 0:

ping -c 1 192.168.0.3
echo The host is down  ## Always changes $? to 0
STATUS=`echo $?`

One better way to do it could be:

一种更好的方法可能是:

until ping -c 1 192.168.0.3; do
    echo "The host is down"
done

Longer version:

更长的版本:

until ping -c 1 192.168.0.3; STATUS=$?; [ "$STATUS" -eq "0" ]; do
    echo "The host is down"
done