1

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 user@"$line" $CMD >> /pathforoutputfile/outputjava.txt

done < /pathforhosts/hosts.txt

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

2
2

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.

3
  • 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 '19 at 19:10
  • Thanks @fabby redirecting output using 2>> helped. Jan 14 '20 at 11:59
  • @SantoshGarole Don't thank me: I just edited RonJohn's original answer. (The best way of thanking is to upvote the answer once you get enough reputation) ;-)
    – Fabby
    Jan 16 '20 at 11:47

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