-   Programming (
-   -   "while read line" doesn't work with ssh in the loop body (

asemaany 03-26-2010 08:39 AM

"while read line" doesn't work with ssh in the loop body
I am trying to read the names of hosts from a file and do a ssh to see if processes are all running or not.
Here is the outer loop that is causing problem:

cat hosts.lst|while read line
ssh $line ps ux

hosts.lst is a text file that has the host names in each line.
The problem is that the loop just breaks after the first run. Somehow while read line becomes invalid when the body of the loop does the ssh and returns. Any idea why it is happening and how to fix it?

Many thanks for your time and help.

David the H. 03-26-2010 09:20 AM

I'm not sure if this is your problem, but a | pipe makes the processes following it run as a subshell. You can avoid this, and the need for the external cat command, by using a simple file redirection.


while read line; do
    ssh "$line" ps ux
done <hosts.1st

Also, please use [code][/code] tags around your code, to preserve formatting and to improve readability.

grail 03-26-2010 09:47 AM

Hopefully the previous post will fix issue, but I noticed you said:


see if processes are all running or not
Yet you neither capture the output of what the command displays nor do you test the exit
status of ssh to see if it were successful.

Just an observation.

Guttorm 03-26-2010 10:19 AM


I had the same problem before. The problem is that when you pipe into the while loop, the while loop reads from stdin. The ssh command takes over stdin so it messes up the pipe. Add the -n option to the ssh command and it will work.

asemaany 03-26-2010 04:19 PM

Thanks Guttorm
That should solve the problem.

grail 03-28-2010 02:14 AM

Please mark problem as SOLVED

Sorry ... was looking at a cached copy .. Please ignore

All times are GMT -5. The time now is 12:45 AM.