Bash exit status when using while loop

I have a bash script that goes through the ip list and pings them one by one. If the exit status for each ping is 0, then the echo that the node is complete, otherwise the node is unavailable. I can make this work fine, but when the bash script completes the exit, the status is always 0.

What I'm trying to achieve, for example, from 5 ip, if the 3rd one fails, continue through the list and check the rest, but as soon as the script finishes resetting the exit status other than 0 and displays which ip has failed .

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 

early!

+5
source share
1 answer

Your first problem is that by executing cat file | while read cat file | while read , you spawned while in your own subshell. Any variables that it sets will exist only during this cycle, so saving the value will be difficult. Read more about it here.

If you use while read ... done < file , it will work correctly. Make an exit status flag that is zero by default, but set it to one if any errors occur. Use it as a value to exit the script.

 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 
+8
source

Source: https://habr.com/ru/post/1237263/


All Articles