Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
You probably want the & outside of the quotes. –  Brad Gilbert Jul 19 '09 at 18:20
1  
No, that just puts the whole kit and kaboodle in the background and I am unable to type my password. –  Richard Hoskins Jul 19 '09 at 18:55

3 Answers 3

up vote 14 down vote accepted

SSH has an -f swtich 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 should down the client before the command an 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 ther server side:

ssh localhost -f 'screen -d -m sleep 60'
share|improve this answer
    
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
    
gnu.org/software/screen/manual –  Brad Gilbert Jul 19 '09 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'
share|improve this answer
    
You could probably combine the two redirections with &>/dev/null. –  Brad Gilbert Jul 19 '09 at 18:13

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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