Create a single line from the output of multiple shell commands

I am trying to ssh to multiple hosts (thousands of them), grab some command output, and write to a file. But the output of the entire command should be on the same line, separated by a comma, separated by a space, nothing but one line for each host.

So my commands are like ::

ssh $host "hostname; uname -r; echo mypassword| sudo -S ipmitool mc info | grep 'Firmware Revision' " > ssh.out

      

But if I use it like that, it will write all command output to separate lines. (3 lines per host). But all I want is just one line per host, say:

myserver,3.2.45-0.6.wd.514,4.3 (comma or any field separator is fine)

      

How can i do this?

+3


source to share


3 answers


Use bash Array Variables . Append the result of each command ssh

to the array. At the end, echo

all elements of the array. The result will be all the elements of the array on one line. Set IFS

(inner field separator) to the desired separator for each node. (I used ,

.) To handle multiple lines of output from multiple commands in a single ssh session, use tr

delimited newlines to replace lines. (I used a space.)

code

sshoutput=()

for host in host01 host02 host03; do
    sshoutput+=($(ssh $host 'echo $(hostname; uname -a; echo mypassword) | tr "\n" " "'))
done

IFS=,; echo "${sshoutput[*]}";

      



Output

host01.domain.com Linux host01.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword ,host02.domain.com Linux host02.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword ,host03.domain.com Linux host03.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword 

      

0


source


It's not very neat, but it printf

works with use . hostname

and uname -r

are checked for work. I don't know what the output is ipmitool

, so I can't test it.



ssh $host "printf $(hostname),$(uname -r),$(echo mypassword| sudo -S ipmitool mc info | grep 'Firmware Revision')\n" > ssh.out

      

0


source


You can store the output ssh

in a variable and then print it:

ssh_output=$(ssh $host "hostname; uname -r; echo mypassword | sudo -S ipmitool mc info | grep 'Firmware Revision' ")
printf '%s\n' "$ssh_output"

      


0


source







All Articles