Why does an `ssh` or `docker exec` command inside a `while read` loop only process the first line?
AdvancedConceptArrays, conditionals and loops
Answer
The loop reads from stdin, and ssh (also docker exec -i, ffmpeg, mysql) also reads stdin, consuming the rest of the file in the first iteration.
while IFS= read -r host; do
ssh -n "$host" uptime # -n: stdin from /dev/null
done < hosts.txt
# or give the loop its own file descriptor
while IFS= read -r host <&3; do
ssh "$host" uptime
done 3< hosts.txt
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate