当前位置:  开发笔记 > 编程语言 > 正文

使用while循环时Bash退出状态

如何解决《使用while循环时Bash退出状态》经验,为你挑选了1个好方法。

我有一个bash脚本,它通过一个ip列表并逐个ping它们.如果每个ping的退出状态为0,则回显节点已启动,否则节点已关闭.我能够使其完美运行,但是当bash脚本结束时,退出状态始终为0.

我想要实现的是例如5个ip中的第3个如果第3个失败,继续通过列表并检查其余部分但是一旦脚本结束抛出除0以外的退出状态并输出哪个ip失败.

cat list.txt |  while read -r output
do
    ping -o -c 3 -t 3000 "$output" > /dev/null
    if [ $? -eq 0 ]; then
    echo "node $output is up"
    else
    echo "node $output is down"
    fi
done

提前致谢!



1> Mr. Llama..:

你的第一个问题是,cat file | while read你已经while在它自己的子shell中产生了它.它设置的任何变量只会在该循环中存在,因此持久化值将很困难. 关于这个问题的更多信息在这里

如果使用while read ... done < file它将正常工作.创建一个默认为零的退出状态标志,但如果发生任何错误,则将其设置为1.将它用作脚本的退出值.

had_errors=0

while read -r output
do
    ping -o -c 3 -t 3000 "$output" > /dev/null
    if [ $? -eq 0 ]; then
        echo "node $output is up"
    else
        echo "node $output is down"
        had_errors=1
    fi
done < list.txt

exit $had_errors

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有