Loop only iterates once with `ssh` in the body [du

2019-01-07 00:23发布

问题:

This question already has an answer here:

  • ssh breaks out of while-loop in bash [duplicate] 3 answers

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

回答1:

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


标签: bash ssh