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.

  • 1
    You probably want the & outside of the quotes. Jul 19, 2009 at 18:20
  • 1
    No, that just puts the whole kit and kaboodle in the background and I am unable to type my password. Jul 19, 2009 at 18:55

3 Answers 3


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'
  • If I do 'ssh remotemachine -n 'long running command > withremoteredirects 2>&1 </dev/null &' and the client shuts down will the command complete? Jul 19, 2009 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, 2009 at 18:32
  • What about 'nohup' instead of 'screen' on the server side? Jul 19, 2009 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. Jul 19, 2009 at 18:44
  • gnu.org/software/screen/manual Jul 19, 2009 at 18:44

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'
  • 1
    You could probably combine the two redirections with &>/dev/null. Jul 19, 2009 at 18:13
  • @BradGilbert That syntax is not POSIX-compatible; it's hard to argue for sacrificing compatibility in order to save a few characters.
    – tripleee
    Apr 12, 2018 at 11:48

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

  • 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, 2016 at 13:08

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.