[Solved] While read line and if statement not working

I'm looking for some help in figuring why my little bit of code will not process any entries other then the first one in my list.

while read line ;do
        hostname=${line//\"}
        a=`ssh user@$hostname uptime;echo $?`
        if [[ "$a" = "255" ]];then
                dt=`date`
                touch /home/user/email.txt
                echo "To:user@userdomain.com" >> /home/user/email.txt
                echo "Subject: URGENT - $hostname is down" >> /home/user/email.txt
                echo "Content-Type: text/plain" >> /home/user/email.txt
                echo "X-Priority: 1 (Highest)" >> /home/user/email.txt
                echo "X-MSMail-Priority: High" >> /home/user/email.txt
                echo "Connection Failed at: $dt" >> /home/user/email.txt
                /usr/sbin/sendmail -t < /home/user/email.txt
                rm -f /home/user/email.txt
        fi
        rm -f /home/user/email.txt
done < "/home/user/servers.txt"

It connects to the first server in the list just fine, but will not try the 2nd or 3rd entry in the servers list.

Hello,

This problem is link to ssh command that close stdin in standart mode when quit (here, your file "servers.txt").
To resolve this, you can use the option -o BatchMode

Regards.

Try using the ssh -n option.

1 Like

Please use this line.


a=`ssh -o BatchMode=yes user@hostname uptime;echo $?`

Both the -n and -o BatchMode=Yes did the trick, thank you very much.

Unless the while loop is fed by a pipe, there is another solution: use a file descriptor other than the default < == 1<

while read line <&3; do
  ...
done 3< "/home/user/servers.txt"

Just adding my two cents here. I've been there myself, and solved it by closing the ssh connection after connecting to each server and doing what I had to do, so during the next run of the while loop there was no existing connection to "interfere" with the new one I was trying to establish. Just add the word exit before closing the loop, like so:

        rm -f /home/user/email.txt
exit
done < "/home/user/servers.txt"

Hope it helps.
If you have found the answer to your question and everything is working to your satisfaction, please mark this thread as solved for the future reference of other users. Thank you.

1 Like