LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Executing on remote server terminates while loop (https://www.linuxquestions.org/questions/programming-9/executing-on-remote-server-terminates-while-loop-4175603422/)

pgb205 04-07-2017 05:42 PM

Executing on remote server terminates while loop
 
Bash script looks like

#!/bin/bash
local_command1
while read line; do
local_command2;
ssh remotesrv "somecommand";
done< /tmp/file

/tmp/file has multiple lines but if I run as above the script stops after reading only first line. Commenting out ssh remotesrv "somecommand"; makes while loop read entire file as intended. I suspect it's something with having to connect to remote shell that breaks the loop but am not sure.

Please let me know what I am doing incorrectly.

michaelk 04-07-2017 08:04 PM

Does the script stop and you are back and the command line prompt or does your script just hang?

Can you connect to the remote server using ssh from the command line?

Are you using ssh keys?

pgb205 04-07-2017 09:52 PM

Quote:

Originally Posted by michaelk (Post 5694123)
Does the script stop and you are back and the command line prompt or does your script just hang?

Can you connect to the remote server using ssh from the command line?

Are you using ssh keys?

I'm back at the command prompt on the server where the above script was run from. Yes I can connect to the remote server via ssh using keys.

ntubski 04-07-2017 10:45 PM

(Please use [code][/code] tags.)

The reason your script stops is because the ssh command reads from stdin, which means it reads all the rest of your /tmp/file on the first run. You can solve this by redirecting or using the -n option.
Code:

ssh remotesrv "somecommand" < /dev/null
# or
ssh -n remotesrv "somecommand"

ssh(1)

Code:

    -n      Redirects stdin from /dev/null (actually, prevents reading from
            stdin).  This must be used when ssh is run in the background.  A
            common trick is to use this to run X11 programs on a remote
            machine.  For example, ssh -n shadows.cs.hut.fi emacs & will start
            an emacs on shadows.cs.hut.fi, and the X11 connection will be
            automatically forwarded over an encrypted channel.  The ssh program
            will be put in the background.  (This does not work if ssh needs to
            ask for a password or passphrase; see also the -f option.)


pgb205 04-07-2017 11:01 PM

ntubski . thank YOU! I think this helped.


All times are GMT -5. The time now is 06:14 PM.