I am writing a shell script that will ssh to multiple hosts, and perform some operations on them.
my script, test.sh, looks as follows:
cat < $1 | xargs -e -d ' ' -I % ssh % grep "example" /opt/example/test.log
I run it via the following command
./test.sh prod_hosts.txt
and the contents of prod_hosts.txt:
hostname1 hostname2 hostname3 hostname4
I have verified there is no carraige return at the end of this file, yet I am getting the following error:
[ryan@hostname1 ~]$ ./test.sh prod_hosts.txt
ssh: hostname4
: Name or service not known
xargs: ssh: exited with status 255; aborting
It looks like it successfully ssh's into the 4 hosts but then has a blank entry that it is attempting to ssh with, hence the error.
Any idea what I'm missing here? Seems like I'm missing something obvious!
echo '1 2' | xargs -d ' ' -I % echo %
produces:
1
2
<blank line>
whereas echo -n '1 2' | xargs -d ' ' -I % echo %
returns:
1
2
i.e. xargs
decides to generate one more output entry if the input string is ended by newline.
Workarounds:
<hosts.txt xargs -I % <ssh-command>
< <(tr ' ' '\n' < hosts.txt) xargs -I % <ssh-command>