Job control: foreground and background

Beginner · 11 min

Run a command in the background with &, suspend with Ctrl-Z, resume with bg and fg, and manage jobs by %number using jobs, kill and wait.

Before thisSignals and killRedirection

Akamai Developers · 11 min

Job control: foreground and background

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Akamai DevelopersReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Your terminal can run one foreground job at a time, which owns the keyboard. Put a command in the background with a trailing & and the prompt returns immediately.
  • Ctrl-Z sends SIGTSTP and suspends the foreground job. bg resumes it in the background, and fg brings any job back.
  • jobs lists what this shell started. Refer to a job with %N, %+ (current), %- (previous) or %name, and use kill %N or wait %N like a PID.
  • $! holds the PID of the most recent background command, which is what a script needs to wait on it.
  • A background job that tries to read the terminal is stopped by the kernel, and a background job's output still lands on your screen unless you redirect it.

One keyboard, many programs

A terminal has one keyboard. If a program is reading it, a second one cannot also read it, or your keystrokes would go to both. So the shell hands the terminal to one job at a time, the foreground job. The shell itself waits for it. That is why a slow command blocks your prompt.

Anything else you start runs in the background: it has no claim on the keyboard and the shell does not wait for it. A job is the shell’s name for one command or pipeline it has started. The job table is the shell’s own list, and a different terminal has a different table.

This works because of the process groups from the processes lesson. Each job is its own group, and the terminal tracks which group is in front. I ran everything below in a real interactive Bash 5.3 session on macOS.

Starting, suspending, resuming

A trailing & starts a command in the background:

$ sleep 200 &
[2] 16392
$ sleep 300 &
[3] 16396

[2] is the job number and 16392 is the PID. To suspend a foreground job, press Ctrl-Z, which sends SIGTSTP:

$ sleep 100
^Z
[1]+  Stopped                    sleep 100

jobs lists them. -l adds PIDs:

$ jobs -l
[1]+ 16381 Suspended: 18              sleep 100
[2]  16392 Running                    sleep 200 &
[3]- 16396 Running                    sleep 300 &

The 18 is SIGTSTP’s number on macOS. The + marks the current job, the one a bare fg or bg uses, and the - the previous one.

bg resumes a stopped job in the background by sending it SIGCONT:

$ bg %1
[1]+ sleep 100 &

fg pulls one to the front, and Ctrl-C then stops it like any foreground command:

$ fg %2
sleep 200
^C
$ fg
sleep 300
^C
$ jobs
[1]+  Running                    sleep 100 &

The forgot-the-ampersand case is the useful one: start the command, press Ctrl-Z, type bg. Nothing restarts.

Job specs

Wherever a PID is accepted, kill and wait take % forms: %1 is job 1, %% or %+ the current job, %- the previous one, %sleep the job whose command starts with that word.

$ kill %1
$ jobs
[1]-  Terminated: 15             sleep 100
[2]+  Running                    sleep 50 &

A finished job is reported once, then removed from the list. A %1 is only meaningful in the shell that holds it: my attempt to wait %1 after the job had already been reported failed with bash: wait: %1: no such job and status 127.

Background jobs still use your terminal

Starting something in the background does not detach it. Its output still goes to the same screen:

$ (echo done-quietly; sleep 1; echo "bg finished") &
[2] 16445
$ done-quietly
bg finished

The text landed in the middle of my prompt. Redirect > file 2>&1 when you start it if you want quiet. Input is stricter. A background job that tries to read from the terminal is stopped by the kernel:

$ cat &
[2] 16497
$ jobs
[1]-  Running                    sleep 100 &
[2]+  Stopped                    cat

cat with no file reads the keyboard, which it does not own, so it froze. Feeding it needs fg.

Scripts and $!

Job numbers are an interactive feature. In a script you hold on to the PID. $! is the PID of the most recent background command:

$ sleep 50 &
[2] 16514
$ echo "last bg pid: $!"
last bg pid: 16514

Save it straight away (pid=$!), because the next & overwrites it, and later wait "$pid" collects its exit status, as in the signals lesson where wait returned 143 for a killed job. Scripts run without job control by default, so Ctrl-Z, fg and bg are not for them. set -m turns it on, but you rarely need it.

About the video

“Master the Linux Command Line: Background & Foreground Jobs to Swap Tasks with the fg and bg Command” is a 10-minute 44-second video from Akamai Developers, published January 2022. Its description lists chapters: what a foreground task is, what a background task is, moving a task to the background and back, practical examples, backgrounding immediately, alternating between background tasks and foregrounding a specific one. I could not read a transcript, so I am going by those chapter titles and the English-language channel. A shorter video from You Suck at Programming on bg and & is linked as a second view.

Where this fits

Background jobs belong to your shell, and when the shell exits they usually go with it. Keeping them alive is the next lesson: nohup, disown and tmux.

Check yourself

  1. 01You started a long command and forgot the &. How do you move it to the background without restarting it?

    Press Ctrl-Z to suspend it, then type bg. It continues running in the background from where it stopped.

  2. 02What is the difference between %1 and 1 when used with kill?

    %1 is job number 1 in this shell's job table, and 1 is process ID 1. Job numbers only exist inside the shell that started them.

  3. 03A background job prints text while you are typing. How do you keep it quiet?

    Redirect its output when you start it, for example cmd > out.log 2>&1 &. Background jobs keep writing to the terminal otherwise.

  4. 04In a script, how do you get the PID of the command you just backgrounded?

    Read $! right after the command. It is overwritten by the next background command, so copy it into a variable at once.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark