I want to run some script through ssh and detach it, so it run even after ssh session is closed. I need to do this with sudo.

I can run some script but I am not able to detach it. I tried following commands:

ssh -t "sudo -b nohup some_script"


ssh -t "sudo nohup some_script &"

Neither of above worked. Every time I get communicate "Connection to closed." and no process is running on server.

I have also tried to do it with screen:

ssh -t "sudo screen -S script -md some_script"

It did not work either, even though command works when I enter it on server locally. How can I do it then?

  • Do you mean the script needs to be run with sudo? I’d try: ssh -t 'sudo sh -c "nohup some_script &"' – dessert Jan 18 at 12:40
  • I have managed to do it with tmux, but I really would like to know why can'I I do it other way. – sbagin13 Jan 18 at 13:07
  • Thanks, I saw that already, but I don't know why this solution doesn't work for me. – sbagin13 Jan 18 at 13:38
  • 1
    It would really help if you could edit your question and explain how each of these "didn't work". Did the command not run at all? Did it run but was stopped when you disconnected? Something else? Telling us how they failed will let us understand why they failed and possibly answer you. – terdon Jan 18 at 15:21

I did small survey and found this similar question on Stack Overflow. At all you must add path to the script or must go inside the directory, where the script is located:

ssh remote-host -t "sudo -b sh -c 'nohup /path/some_script > /dev/null 2>&1 &'"
ssh remote-host -t "sudo -b sh -c 'cd /path; nohup ./some_script > /dev/null 2>&1 &'"

Without sh -c or bash -c the ampersand & at the end breaks the command in some way.

I couldn't manage to use disown for this purpose, but setsid works well:

 ssh remote-host -t 'sudo -b setsid /path/some_script'
  • Any idea why I can't start and detach script on guest system (Ubuntu server) in VirtualBox? In the other direction it works. I can start session on host from guest. – sbagin13 Feb 12 at 13:55
  • Hi, @sbagin13, I do not have any experience with VirtualBox. Is it possible to be an issue with the $PATH envvar? Try to redirect the output to some file instead of /dev/null, maybe this log will provide some useful information. – pa4080 Feb 12 at 14:47

You can try using disown to avoid the process being killed after you close you ssh session.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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