V

2012-11-25
ssh draining stdin

We had a script which does some remote commands based on preconditions. It stopped processing the loop after the first time the condition was true:

#!/bin/sh
DATA="host1 1
host2 2
host3 3
host4 4
host5 5"

echo "$DATA" | while read host num; do
    if [ $(( num % 2 )) -eq 1 ]; then
        ssh $host "echo $num"
    fi
done
$ sh test1.txt 
1
$

I found that ssh was reading all the remaining data and the next read failed and the loop ended. When redirecting ssh's stdin from /dev/null everything worked as expected. As alternative to redirecting stdin you can also use the -n switch for ssh (i.e. run ssh -n $host "echo $num" ):

#!/bin/sh
DATA="host1 1
host2 2
host3 3
host4 4
host5 5"

echo "$DATA" | while read host num; do
    if [ $(( num % 2 )) -eq 1 ]; then
        ssh -n $host "echo $num"
    fi
done
$ sh test1.sh
1
3
5
$
Permalink | shell, ssh.
$HOME
Archives

Tags