How to detach a Linux process from shell

Last updated on September 22, 2020 by Dan Nanni

When you execute a Linux command resulting in a background process, the process will be killed automatically if a controlling terminal is closed, or a ssh session is terminated. It is because a shell, which is the parent process of all background processes running in the terminal/ssh session, sends a SIGINT to all its child processes. If you want a process to keep running after a terminal session is over, that is when detaching a Linux process from shell can help.

Here is how you can detach a process from bash shell.

If a given process is running in the foreground, press Ctrl+z to interrupt it.

Then run it in the background.

$ bg
[1]+ my_command &

Finally, type disown along with job sequence number of the backgrounded job.

$ disown %1

disown is a built-in shell command that causes a shell to not send SIGHUP to disowned child processes, thereby allowing them to continue even after the shell process is terminated. Once a background process is disowned by a shell, the process will disappear from a job list when you type jobs command, which means that you can safely close a terminal or log out without killing the process.

When run without any argument, disown removes the most recent job from a job list.

Not all shells support disown, unfortunately. disown is supported in bash and zsh, but shells like csh, tcsh, dash do not support it.

Besides disown, you can also use nohup to detach a Linux process from shell, but in this case, at the time of process launch.

$ nohup <my_command> &

While disown prevents a closing shell from sending SIGUP signals, nohup configures a command to ignore SIGHUP signals sent by the shell. So once any command is launched with nohup, it does not matter whether or not the shell sends out SIGHUP. Any nohup-ed command will continue to run.

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean