Mad-D
Mad-D

Reputation: 4669

Using SSH in while loop loses attribute value

I have a quite weird problem, can't figure out how it is losing the values. I have 5 server name values in clean_file. Let say if i have to SSH 4th server, restart some application then the while loop doesn't complete the loop instead it stops right after 4th value once it starts the application.

grep -v -e"#" $HOST | awk '{print $2"     "$4"     "$5}'| grep -e^windows -e^linux -e^red > $DIRECTORY/clean_file

clean_file looks like

eclipse server101
itunes server111
appDynamics server100
itunes server102
quicktime server133

While Loop & Function for SSH

while read -r line
do 
  #check for application status
  mcstat -q -n $name | grep "Processing"
  if [ $? -eq 0 ]; then
     echo " works like a charm $name"
  else
     i=$name
     checker
  fi
done < "$DIR/clean_file"

function checker(){
    while [ $j -lt 3 ]; do
       ssh $server 'mcell -q -n "'"$i"'"' || echo "error 101"
       sleep 15
       ssh $server 'mcstat -q -n "'"$i"'"' || echo "error 102"
       echo " I made it work like a charm $i"
   j=$((j+1))
   done
}

Output

when all applications are fine and function checker is not called

works like a charm eclipse 
works like a charm itunes
works like a charm appDynamics
works like a charm itunes
works like a charm quicktime

when itunes on server102 is not running, then checker function will be called & it fails to check for quicktime application status on server133

works like a charm eclipse 
works like a charm itunes
works like a charm appDynamics
I made it work like a charm itunes

Upvotes: 0

Views: 85

Answers (1)

Kenster
Kenster

Reputation: 25399

Commands run from inside the while loop have access to the while loop's standard input. ssh normally reads from standard input, so it's consuming the loop's input. To prevent ssh from reading standard input, redirect its input from /dev/null or run it with the -n flag:

ssh $server 'mcell -q -n "'"$i"'"' < /dev/null || echo "error 101"

ssh -n $server 'mcell -q -n "'"$i"'"' || echo "error 101"

Alternately, you could protect everything that runs within the loop at once:

while read -r line
do
    {
        mcstat -q -n $name ...
    } < /dev/null
done < "$DIR/clean_file"

Upvotes: 1

Related Questions