LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   "while read line" doesn't work with ssh in the loop body (http://www.linuxquestions.org/questions/programming-9/while-read-line-doesnt-work-with-ssh-in-the-loop-body-798036/)

asemaany 03-26-2010 07: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:

#/bin/bash
cat hosts.lst|while read line
do
ssh $line ps ux
done

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 08: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.

Code:

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 08:47 AM

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

Quote:

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 09:19 AM

Hi

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 03:19 PM

Thanks Guttorm
That should solve the problem.

grail 03-28-2010 01: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 05:32 AM.