ping的返回值

时间:2015-12-26 00:55:16

标签: bash if-statement return-value

我做了一个名为hosts.txt的文件,其中包含一些网站,用脚本测试每个网站上的ping。我想用我的脚本做的是我想循环遍历包含不同网站的每一行,它应该告诉网站是上升还是下降(通过测量每个上面的ping命令)

我的问题是我真的不知道如何获取ping命令的返回值,所以万一网站启动时应该说“找到''网站名称'”或找不到。我一直在研究,也试过了!命令和if语句中的不同方式,但它们似乎都不起作用。

我的代码:

#!/bin/bash
echo
echo "Monitoring hosts from file hosts.txt ..."
echo
echo
egrep -v '^(#|$)' hosts.txt | while read line; do #put the egrep value
#which is the lines in hosts.txt, and loop through each one of them

        if [ ping $line ];then
        echo "$line is up"

        else
        echo "$line is not up"
        fi

done

echo

2 个答案:

答案 0 :(得分:1)

您需要使用$?特殊变量。

例如:

ping $line
pingResponse = $?

if [ $pingResponse -eq 0 ];then
    echo "$line is up"
else
    echo "$line is not up"
fi

答案 1 :(得分:0)

您可以测试布尔值,如:

[[ `ping  $line` ]]

   #!/bin/bash
    echo
    echo "Monitoring hosts from file hosts.txt ..."
    echo
    echo
    egrep -v '^(#|$)' hosts.txt | while read line; do #put the egrep value
    #which is the lines in hosts.txt, and loop through each one of them

            if [[ `ping $line` ]];then
            echo "$line is up"

            else
            echo "$line is not up"
            fi

    done