The overall question here is - how do I automate sshing into a machine, running a script, and exiting without killing the script? I know that this has been answered several times, but I'm not having luck with the solutions I've found.

The details:

I have code running on several machines that I ssh into.

Right now, I'm doing the following in a terminal:

ssh machine1@host (log in automatically with key)
screen -S screen_name
<keystroke C-a-d>

Time consuming, and more importantly, prone to errors (open a screen and exit it without running the script, etc.).

I'd like to automate this. My first thought was to try to replicate this exactly. I tried xdotool to send the keystrokes, but my environment is command line only, and it seems like the wrong tool for the job. Similarly expect looks like it could be used instead of xdotool, but again, probably the wrong way to do it.

I also tried using nohup instead of screen, by doing nohup ./script.sh &

but when I log out of the ssh session and come back, it looks like the script stopped running when I logged out. As far as I can tell, nohup is the right way to do it.

  • Why do you think the background nohup stopped running? @l0b0's answer is proposing exactly what you're doing, just removing the step of manually logging in. There's no reason a command that's backgrounded via nohup should stop running, unless it actually finished . . .
    – ernie
    Apr 11, 2014 at 23:27
  • I'm trying to figure out why now. I'll update the question when I do, but right now I have no idea.
    – user327301
    Apr 11, 2014 at 23:46

1 Answer 1



$ ssh host 'nohup your-command &' &

Here's an example:

$ ssh localhost 'nohup sleep 10 &' &
[1] 12345
$ sleep 5 && ps x | grep '[s]leep 10'
24044 pts/0    S      0:00 ssh localhost nohup sleep 10 &
24054 ?        S      0:00 sleep 10

This starts an SSH connection, runs sleep 10 in the background on the target host (which happens to be your local host), and checks the process list (ps) to verify that it's still running after ssh finishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.