Help, ssh is eating up all my standard input!

If you're running ssh inside a shell script that's reading from standard input (stdin), beware that the ssh execution will drain stdin unless you use the -n option.

For example, take this loop:

while read host; do
   ssh "$host" hostname
done < /path/to/list-of-hosts

This will only loop once even if the file has multiple lines, since ssh is reading stdin attached to the whole loop and forwards it to the stdin of the "hostname" command executed on the remote host (which happily discards it, not reading from stdin at all).

To avoid this, use the -n option:

while read host; do
   ssh -n "$host" hostname
done < /path/to/list-of-hosts

Of course, using ssh like that only makes sense when using public key authentication.

Tags:

Comments

Vide's picture

Wth your post finally I understood why ssh didn't loop "as expected", without the -n option. Thanks! Smile