Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop only iterates once with `ssh` in the body [duplicate]

Tags:

bash

ssh

I often see questions which are essentially the same as...


My while loop only iterates once when I call ssh in the body of the loop.
while read -r line; do
    ssh somehost "command $line"
done < argument_list.txt

like image 483
chepner Avatar asked May 29 '14 16:05

chepner


1 Answers

ssh also reads from standard input, so the first call to ssh consumes the rest of argument_list.txt before the next call to read. To fix, either redirect ssh's standard input from /dev/null using either

ssh somehost "command $line" < /dev/stdin

or

ssh -n somehost "command $line"

In the event that ssh really does need to read from standard input, you don't want it reading more data from argument_list.txt. In this case, you need to use a different file descriptor for the while loop.

while read -r line <&3; do
    ssh somehost "command $line"
done 3< argument_list.txt

bash and some other shells also allow read to take a -u option to specify the file descriptor, which some might find more readable.

while read -r -u 3 line; do
    ssh somehost "command $line"
done 3< argument_list.txt
like image 136
3 revs, 2 users 97% Avatar answered Sep 30 '22 19:09

3 revs, 2 users 97%