BASH - Need to echo for loop output to one line

I'm trying to echo the release version of some of our Linux servers. Typically I do these types of things by "catting" a text file with the host names, "ssh-ing" to the host and running my string.

This is what I've written

for i in `cat versions.txt` ; do echo $i ; ssh $i cat /etc/issue | grep release ; done

This works, but I get output like

ServerName
Red Hat Enterprise Linux Server release 5.6 (Tikanga)

I'm trying to get it to look like

ServerName Red Hat Enterprise Linux Server release 5.6 (Tikanga)

I've looked around the forums and messed with printf and echo -n but I can't seem to get the syntax right. Any help is appreciated.

Why not run grep on the server instead of cat? Less traffic.

Also, a while loop is more appropriate.

Use printf to print a string without adding a newline at the end.

ssh -n is used to prevent ssh from 'eating' all the input in versions.txt (otherwise it would run once then stop).

If ssh fails, it prints "couldn't login", so you don't get a line like server1 server2 server3 server4 server4-information when server1-3 fail to login.

while read i
do
        printf "%s " "$i"
        ssh -n $i grep release /etc/issue || echo "couldn't login"
done < versions.txt
1 Like

This is great, and exactly what I needed. Thank you very much! :b:

I have a quick question, just to increase my own knowledge.

Why is a "while" loop better for this? Is that just a personal preference?

The reason the while loop is better is because the for loop requires back-ticks this invokes another instance of the shell to execute, also the cat external executable needs to be loaded to read the file.

In contrast while can use the shell internal read command to load the file.

The assumption here is your versions.txt file has 1 host name per line and not something like:

server1 server2 server3
server4 server5 server6

And the `cat file` stores the whole file in memory before the loop starts.
The while loop reads the file line by line, so only one line is in memory.

Most importantly, it doesn't do quite exactly what you think it does -- splitting across whitespace, not lines. If you try to handle data any more complex than that, or there happens to be anything you didn't expect in it, you'll be in for a big surprise.

It also tends to break down a lot. There's a limit to how much you can cram in one statement, surprisingly small on some systems.

Also, it's inefficient because it crams it all into one statement. Just because you can doesn't mean you should.

See useless use of cat, useless use of backticks, and particularly dangerous backticks.