Skip to content

Detach foreground process from terminal in Linux

homepage-banner

Introduction

If you use the Bash shell, you’ve probably run commands that take a while to complete. Sometimes, you might start a command and then realize that you need to close the terminal window or log out of the system. If you do this, the command will stop running. However, there is a way to keep a command running even after you log out of the system. This is where the disown command comes in handy.

What is Disown?

The disown command is a Bash shell built-in that allows you to remove a job from the shell’s job control. When you disown a job, it continues to run in the background even after you close the terminal window or log out of the system. This means that you can start a long-running process and then detach it from the terminal so that it continues to run even after you log out.

How to Use Disown

To use the disown command, you first need to start a command or a job in the background. For example, you might start a long-running command like this:

./long_running_command &

The & character at the end of the command tells Bash to run the command in the background. Once the command is running, you can use the jobs command to see a list of all the jobs that are currently running in the shell:

$ jobs
[1]+  Running                 ./long_running_command &

The [1] in the output indicates that the long_running_command job is job number 1. You can then use the disown command to remove the job from the shell’s job control:

disown %1

The %1 in the command tells Bash to disown job number 1. Once you’ve disowned the job, you can safely close the terminal window or log out of the system without worrying that the job will stop running.

Run the program in the background

bg %1

Hand over the background process to init/systemd (process 1)

  • Use disown -h jobspec to make a job ignore HUP signal.
  • Use disown -ah to make all jobs ignore HUP signal.
  • Use disown -rh to make a running job ignore HUP signal.

Conclusion

The disown command is a useful tool for anyone who works with long-running processes in the Bash shell. By using disown, you can detach a process from the terminal and let it continue running in the background even after you log out of the system. This can be a real lifesaver when you need to start a long-running process and then leave it running unattended.

Leave your message