Bash – Redirecting bash loop output to variable specific files

bashlinuxscriptingshellshell-script

this should probably be obvious to me, but I've been stuck for some time.

I'm trying to write a very simple bash loop to take a list of servers, retrieve some specific info from them, and save the output to a file based on that host address on the starting machine.

Code currently looks like:

#!/bin/bash

SERVER_LIST=/path/to/hosts

while read REMOTE_SERVER
do
    {
    ssh user@$REMOTE_SERVER 'show_stat_from_shell_command' 
} > "$REMOTE_SERVER"
done < $SERVER_LIST

The result from the above produces only a single output file for the first host in my list and then exits.

To head off some of the more obvious solutions, Ansible etc. are not an option due to this being a very restricted environment. For the same reason using a multi-shell or tmux is also not an option (I can only log into one system at a time from my host).

So, if someone could tell me exactly how I'm messing this up it would be appreciated!

Best Answer

Replace

ssh user@$REMOTE_SERVER 'show_stat_from_shell_command'

by

ssh user@$REMOTE_SERVER 'show_stat_from_shell_command' </dev/null

to prevent ssh reading from stdin ($SERVER_LIST) too. Or use ssh's option -n.


-n: Redirects stdin from /dev/null (actually, prevents reading from stdin).

Related Question