代码:
for i in {1..5}
do
PING=`ping -nq -w5 -c1 8.8.8.8`
C=`echo $PING | grep "100% packet loss"`
if $C; then
echo "ok"
else
echo "not connected"
fi
done如果我使用8.8.8.8,它可以工作,但当我将其更改为ip时,它没有响应,如29.0.0.0,错误发生:"There no PING command“。出什么问题了?
发布于 2014-07-18 20:21:36
if $C; then在这里,命令$C和将被执行,它的返回代码决定采用哪个分支。
但您真正拥有的是命令的输出,您想要检查它是否为空。
将其更改为:
if [[ -z $C ]]; then-z检查字符串是否为空。如果为空,则不匹配"100%丢包“(ping已通过)。
摘自手册:
-z string
True if the length of string is zero.发布于 2014-07-18 20:22:28
if [ -z "$C" ]; then-z是零长度检查,$C是您的变量。它放在[]中是因为这是test命令的别名,如果输入正确,则返回true,否则返回false。
你也可以这样做
if [ "$C" = "" ]; then这将对空字符串执行更传统的检查。
如果你真的很确定你想要什么,你也可以走得更远:
if grep -q "100% packet loss" <<<"$PING"; then
echo "not connected"
else
echo "ok"
fi它使用grep的-q标志为我们检查结果。
发布于 2014-07-18 20:24:28
if后面的代码应该是命令列表,而不是字符串。您需要显式测试字符串的长度是否为零;一种方法是使用
if [[ -z $C ]]; then
# No output, so at least one packet got through
echo "ok"
else
echo "not connected"但是,更好的解决方案是不检查输出,而是检查grep的退出状态。
if ping -nq -w5 -c1 8.8.8.8 | grep -q "100% packet loss"; then
# All packets lost, no connection
echo "not connected"
else
echo "ok"
fi在这里,-q选项禁止所有输出。实际上,您并不关心包含"100%数据包丢失“的行;您只关心grep是否能找到它。
https://stackoverflow.com/questions/24824712
复制相似问题