Processes and jobs
Linux commands: bg
Learn how the Linux bg command resumes a job you suspended with ctrl-Z, running it in the background so you can keep working in the terminal.
When a command is running in the foreground, you can suspend it by pressing ctrl-Z.
The command stops immediately, and you get the shell prompt back. The program is still there, frozen, waiting.
bg resumes it in the background. It keeps running, but it no longer blocks the terminal, so you can do other work in the meantime.
Let’s see it with a command that takes a while:
sleep 300
^Z
[1]+ Stopped sleep 300
The shell tells us it’s job number 1 and that it’s stopped. Now resume it in the background:
bg
[1]+ sleep 300 &
The trailing & in that message is the shell’s way of saying “this now runs in the background”. Run jobs and you’ll see it as Running. Five minutes later it finishes on its own and the shell prints [1]+ Done sleep 300.
This is the pattern I use when I start a long build in the foreground and then realize I need the terminal. ctrl-Z, bg, and the build keeps going.
With more than one suspended job, pass the job number. In this example I have 2 commands stopped:
![Terminal output showing jobs command with two stopped jobs labeled [1] and [2], both running top command in different directories](/images/linux-command-bg/Screen_Shot_2020-09-03_at_16.06.18.png)
I can run bg 1 to resume job #1 in the background.
I could also run bg without any argument. The default is the current job, the one marked with + in the jobs list.
One thing to know: not every program is happy in the background. top, like in the screenshot, wants to draw on the terminal. Send it to the background with bg and the shell stops it again right away, because a background job is not allowed to take over the screen. That’s not a bug. Bring it back with fg when you want to look at it.
If you type bg with nothing suspended, the shell says so:
bg
bash: bg: current: no such job
Run jobs to see what’s there before you resume anything.
The
bgcommand works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Lesson completed