Bash script is helpful if you want to do something automatically, especially in batch mode. Recently I want to upgrade a package on several hosts so I write a small script within it there is a while loop to read hosts from a file and ssh to every one and run some commands. However, the weird thing is that commands only done on the first host apparently and the while loop broke.
That did surprised me a little, see below simple scripts
The output as I expected was
However, the out was
Apparently something gone wrong, as I expected if comment the line ssh $host
“echo hello”, it works fine and print three *ssh to
So here comes the short answer, ssh eat the stdin of the while loop, so host2\nhost3\n was never sent to the while loop but eaten by ssh, we can verify that like below.
We’ll get the output like
A simple solution is use ssh with -n option to redirect its stdin from /dev/null like below.
It will works as we expected.