I have a bash script that goes through a list of ip's and pings them one by one. If the exit status for each ping is 0, then echo that the node is up, else the node is down.I am able to get this to work perfectly, but when the bash script ends the exit status is always 0.
What I am trying to achieve is for example out of 5 ip's if the 3rd one fails, to continue through the list and check the rest but once the script ends throw an exit status other than 0 and output 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
thanks in advance!
Your first problem is that by doing cat file | while read
you've spawned the while
in its own subshell. Any variables it sets will only exist during that loop, so persisting a value will be difficult. More info on that issue here.
If you use while read ... done < file
it will work correctly. Make an exit status flag that defaults to zero, but set it to one if any errors occur. Use it as your script's exit value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With