3

I want to start a shell script that resides on a remote machine. When I use

ssh [email protected] /path/to/script.sh

it needs the ssh connection to be open until the script has terminated.

But I need the script to continue to run, even after I close the ssh connection until the script finishes by itself. I just want to start a process and then forget about it.

How can I do this using ssh?

Thanks a lot!

P.S.: This is not a duplicate of this stackechange question.

Gary Czychi
  • 307
  • 1
  • 3
  • 11
  • 2
    This over on stackoverflow may help: [Getting ssh to execute a command in the background on target machine](http://stackoverflow.com/questions/29142/getting-ssh-to-execute-a-command-in-the-background-on-target-machine) – Mark Plotnick Feb 17 '17 at 20:24

1 Answers1

6

I believe the problem is that when the SSH session is closed (by hitting ctrl-c, or closing the xterm), a HUP is sent to the process. To fork the process to background, add &, and to block the hup, use nohup:

ssh [email protected] 'nohup sleep 300 >/dev/null 2>/dev/null </dev/null &'

The ssh should start and the process will run on example.com in the background.

If you wish to monitor its progress, you can use screen, if you wish to do that then something similar to this will help:

ssh [email protected] -t 'screen -D -RR -S this /bin/sleep 300'

This creates a screen session named 'this' (-S), detaches an already running screen if attached elsewhere and reattaches here. Then starts /bin/sleep with a 5min wait.

Ed Neville
  • 1,330
  • 10
  • 11
  • If I wanted to save the output of the command to a file on the remote machine, where would the file path go (which dev/null should be replaced)? – Gary Czychi Feb 17 '17 at 22:50
  • `>/dev/null` redirects the output of STDOUT to `/dev/null`. `2>/dev/null` redirects STDERR to `/dev/null`. `/dev/null` – dpw Feb 17 '17 at 23:04