我有一个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
提前致谢!
你的第一个问题是,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