0

This question already has an answer here:

I have 100 servers and i need to login to them with ssh from central server using script: i tried below with this i should get the version redirected to the file which will be stored at central server.

#!/bin/bash

CMD='java -version'
while read line
do
    ssh -n sgarole@"$line" $CMD >> /pathforoutputfile/outputjava.txt

done < /pathforhosts/hosts.txt

But I am not getting output generated in file /pathforoutputfile/outputjava.txt

marked as duplicate by Rui F Ribeiro, terdon shell-script Jun 6 at 16:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

That command does in fact write to stderr.

ron@haggis:~$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment (build 11.0.2+9-Ubuntu-3ubuntu118.04.3)
OpenJDK 64-Bit Server VM (build 11.0.2+9-Ubuntu-3ubuntu118.04.3, mixed mode, sharing)
ron@haggis:~$ 
ron@haggis:~$ java -version 2> foo.txt
ron@haggis:~$ cat foo.txt
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment (build 11.0.2+9-Ubuntu-3ubuntu118.04.3)
OpenJDK 64-Bit Server VM (build 11.0.2+9-Ubuntu-3ubuntu118.04.3, mixed mode, sharing)

Thus, you should redirect using 2>> instead of >> in

ssh -n sgarole@"$line" $CMD >> /pathforoutputfile/outputjava.txt

One other thing I noticed is that you don't seem to be mentioning the remote host names in /pathforoutputfile/outputjava.txt.

  • Doing an ordinary > redirect after done removes the need to manually delete the output file each time the script is being rerun: ...; done <inputfile >outputfile And the host could simply be outputted with printf '%s\n' "$line" in the loop. – Kusalananda May 27 at 19:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.