Most programs, when invoked from the shell, run in the foreground taking over your terminal and preventing you from doing other work without opening a new terminal window. But there’s a better way: bagrounding and foregrounding processes.
This works on both Linux and macOS, however there are slight differences. Here’s a simple example to help you understand how to background and foreground a process…
Let’s say you have bashtop running. To background the process, all you have to do is press ctrl
+ z
. To bring it back to the foreground, all you have to do is type fg
.
What about backgrounding multiple processes? You can do that. Let’s open and background vim and a YouTube video in mpv player.
NOTE: if you’re confused about playing a youtube video with mpv, check out this article. This one goes into even more details.
So now we have three backgrounded processes. First let’s see how to list all the backgrounded processes. You can do that with jobs
.
Now that you have multiple processes backgrounded, if you type fg
, you’ll find that the process that will be forgrounded is the last process you backgrounded. So how can you choose which process to bring to the forground ?
When you use the jobs
command to list all the backgrounded processes, you’ll notice that each process has a process number. In the screenshot above bashtop is process number 1, vim is number 2 and mpv is number 3.
On Linux, to choose which process you want to foreground you can type fg number_of process
. For example, if you want to foreground vim, you’ll type fg 2
. On macOS however, you will have to type fg vim
.
Is there a way to send a process straight to the background? Yes there is. Let’s say you want to open another vim job and send it directly to the background. All you have to do is type vim file_name &
There’s one more thing. If you want to logout (ctrl
+ d
on Linux ) while jobs are active in the background, the action will be prevented and your shell will tell you that you have jobs running in the background. If you try to logout a second time, you will be logged out and the backgrounded jobs will terminate.