Background Mode
Learn how to run our application in the background and use the terminal for the next commands.
Let’s suppose that we run a GUI application in the terminal window. Then, we cannot use this window for typing the Bash commands. The GUI program controls it and prints the diagnostic messages there. The terminal window becomes available again when the application finishes.
We can run the GUI application in the background mode. Then, the terminal window stays available, and we can use it normally. Add the ampersand (&
) at the end of a Bash command to launch it in the background mode. Here is an example:
notepad++ test.txt &
After this command, we can type text in the terminal window. The only problem is that the editor still prints the error messages from Notepad++ here. These make it inconvenient to use this terminal window.
We can detach the running GUI application from the terminal window completely. Let’s do it with the disown
Bash built-in, and dall disown
with the -a
option this way:
notepad++ test.txt &
disown -a
Now, Notepad++ does not print any messages in the terminal. The disown
call has one more effect. It allows us to close the terminal window and keep the editor working. Without the disown
call, Notepad++ finishes when we close the terminal.
We can combine Notepad++ and disown
calls into one command. It looks like this:
notepad++ test.txt & disown -a
The -a
option of the disown
command detaches all programs that work in the background. If we skip this option, we should specify the process identifier (PID) of the program to detach. PID is a unique number that the OS assigns to each new process.
Let’s suppose that we want to call disown
for the specific program. We should know its PID. Bash prints the PID of the background process when we launch it. Here is an example:
notepad++ test.txt &
[1] 600
The second line has two numbers. The second number 600 is PID. The first number [1]
is the job ID. We can use it to switch the background process to the foreground mode. The fg
command does it this way:
fg %1
If we want to detach the Notepad++ process from our example, we call disown
this way:
disown 600
If we want to list all programs that work in the background, use the jobs
Bash built-in. When we call it with the -l
option, it prints both job IDs and PIDs. We use it this way:
jobs -l
This command lists all background processes that we launched in the current terminal window.
We can call Notepad++ and detach it from the terminal in a single command. In this case, we should use the special Bash variable called $!
. It stores the PID of the last launched command. After we pass this PID to the disown
call, and we are done. Here is an example of how to apply this approach:
notepad++ test.txt & disown $!
Get hands-on with 1200+ tech skills courses.