43

How can I use ssh to run a command on a Unix machine and exit before the command completes?

For instance, if I type

ssh localhost 'sleep 60 &'

ssh hangs on my terminal until sleep completes, even though sleep is run in the background.

3 Answers3

42

SSH has an -f switch which does exactly the same as using nohup on your client but makes it possible that ssh asks for a password. Use it like that:

ssh localhost -f 'command'

But: SSH will still live in background, so if you shut down the client before the command on the server finished, it will be aborted. If you want the ssh connection to be closed after executing the command, you can use screen on the server side:

ssh localhost -f 'screen -d -m sleep 60'
Pang
  • 955
Martin
  • 644
  • If I do 'ssh remotemachine -n 'long running command > withremoteredirects 2>&1 </dev/null &' and the client shuts down will the command complete? – Richard Hoskins Jul 19 '09 at 18:24
  • Afaik no. I ssh connections is lost, the ssh daemon should terminate all terminals "inside" ssh. Ans since the terminal started the command they would be terminated to, since thier parent process terminated. But it's worth trying ;) – Martin Jul 19 '09 at 18:32
  • What about 'nohup' instead of 'screen' on the server side? – Richard Hoskins Jul 19 '09 at 18:33
  • @Brad Gilbert Nothing? I can think of a few things, but one thing the don't have in common, is that 'screen' isn't available on all POSIX machines. – Richard Hoskins Jul 19 '09 at 18:44
  • http://www.gnu.org/software/screen/manual/ – Brad Gilbert Jul 19 '09 at 18:44
  • screen and nohup have different uses. You can't rejoin a nohup session, only view what it has done. – Brad Gilbert Jul 19 '09 at 18:57
  • @Brad Gilbert I know. Screen isn't always available, and anyway it was being used in the example to prevent sleep from being killed when the ssh connection closed. – Richard Hoskins Jul 19 '09 at 19:04
8

Use nohup, stdout/stderr redirection, and run the command in the background:

 nohup ssh localhost 'sleep 60' >/dev/null 2>/dev/null &

EDIT: Or even better, just use the ssh's -f parameter:

ssh -f localhost 'sleep 60'
neu242
  • 1,416
3

Or after login in using ssh, start screen if you may want to come back later, to look at the progress or output.

Arjan
  • 31,163
  • 1
    You can also use "tmux" which I personally find easier to configure. Both applications are pretty much equivalent with each having its pros and cons. – mzuther Feb 14 '16 at 13:08