Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating SSH session executed by bash script

Tags:

I have a script I can run locally to remotely start a server:

#!/bin/bash ssh [email protected] <<EOF   nohup /path/to/run.sh & EOF echo 'done' 

After running nohup, it hangs. I have to hit ctrl-c to exit the script.

I've tried adding an explicit exit at the end of the here doc and using "-t" argument for ssh. Neither works. How do I make this script exit immediately?

EDIT: The client is OSX 10.6, server is Ubuntu.

like image 649
mahemoff Avatar asked Aug 16 '11 21:08

mahemoff


People also ask

How do I terminate an SSH session?

The first way to disconnect from an SSH session is with the exit command. Issue this command on the remote terminal that you are currently logged in to. The second way to disconnect from an SSH session is with the logout command.

How do I stop a bash script execution?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.

How do you terminate a shell script?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.


2 Answers

I think the problem is that nohup can't redirect output when you come in from ssh, it only redirects to nohup.out when it thinks it's connected to a terminal, and I the stdin override you have will prevent that, even with -t.

A workaround might be to redirect the output yourself, then the ssh client can disconnect - it's not waiting for the stream to close. Something like:

nohup /path/to/run.sh > run.log & 

(This worked for me in a simple test connecting to an Ubuntu server from an OS X client.)

like image 57
martin clayton Avatar answered Oct 06 '22 02:10

martin clayton


The problem might be that ...

... ssh is respecting the POSIX standard when not closing the session  if a process is still attached to the tty. 

Therefore a solution might be to detach the stdin of the nohup command from the tty:

nohup /path/to/run.sh </dev/null & 

See: SSH Hangs On Exit When Using nohup

Yet another approach might be to use ssh -t -t to force pseudo-tty allocation even if stdin isn't a terminal.

man ssh | less -Ip 'multiple -t'  ssh -t -t [email protected] <<EOF   nohup /path/to/run.sh & EOF 

See: BASH spawn subshell for SSH and continue with program flow

like image 30
chad Avatar answered Oct 06 '22 01:10

chad