Foreground and Background Processes
Every external command that Bash runs becomes a process: a running program with its own process ID (PID), its own memory, and a parent process, which is usually the shell that started it. A process runs either in the foreground or in the background. In the foreground, the shell waits for the command to finish before it reads the next one, and the command owns the keyboard: what you type goes to it, and Ctrl + C stops it. In the background, the shell starts the command and immediately continues, so the command runs while you, or the rest of the script, do something else.
This lesson explains what the two modes mean, how the terminal decides which processes receive keyboard input and signals, how background processes behave differently in an interactive shell and in a script, and what happens to them when the shell exits. The following lessons go deeper into each tool: the & operator (136), jobs, fg and bg (137), wait (138), $! and $$ (139) and signals (140-141).
Foreground: the Shell Waits
Almost every command in the earlier lessons ran in the foreground. Bash starts the program, waits until it ends, stores its exit status in $? (lesson 117), and only then prints the next prompt or runs the next line of the script. Two foreground sleep 2 commands therefore take four seconds:
sleep 2; sleep 2
While a foreground command runs, it also receives the keyboard: if it reads input, it gets what you type, and the shortcuts Ctrl + C (interrupt) and Ctrl + Z (suspend) are delivered to it, not to the shell.
Background: the Shell Continues
An & at the end of a command starts it in the background. The shell does not wait; it moves on immediately. wait (lesson 138) pauses until background commands have finished. Timing the two styles side by side:
start=$(date +%s.%N)
sleep 2; sleep 2
echo "sequential: $(awk -v s="$start" -v e="$(date +%s.%N)" 'BEGIN { printf "%.1f", e - s }') s"
start=$(date +%s.%N)
sleep 2 & sleep 2 & wait
echo "background: $(awk -v s="$start" -v e="$(date +%s.%N)" 'BEGIN { printf "%.1f", e - s }') s"
sequential: 4.0 s
background: 2.0 s
In the second line, both sleep commands started at once and ran side by side. date +%s.%N prints the time in seconds with nanoseconds (a GNU date feature), and awk computes the difference, because Bash arithmetic has no fractions.
The order of events makes the difference visible:
echo "1. before"
{ sleep 1; echo "3. background job done"; } &
echo "2. shell continues at once (status of & is $?)"
wait
echo "4. after wait"
1. before
2. shell continues at once (status of & is 0)
3. background job done
4. after wait
A whole group in { } can be sent to the background; Bash runs it in a separate child process. Starting a background command always succeeds as far as $? is concerned (status 0), because at that moment the command has only just started. Its real exit status becomes available later, through wait (lesson 138).
The Terminal and Process Groups
Who receives the keyboard is decided by process groups. Each process belongs to a group, identified by a process group ID (PGID), and the terminal has exactly one foreground process group at a time. Keys typed at the terminal are delivered to that group, and so are the signals generated by Ctrl + C (SIGINT) and Ctrl + Z (SIGTSTP). Processes in other groups are in the background as far as the terminal is concerned.
ps shows these relationships. A + in the STAT column marks processes in the terminal's foreground group. The script below starts a background sleep and lists itself and the sleep:
sleep 3 &
ps -o pid,ppid,pgid,stat,comm -p $$,$!
wait
Run inside a terminal (the test used the script command to provide one), the result was:
PID PPID PGID STAT COMMAND
930 928 930 Ss+ bash
931 930 930 S+ sleep
$$ is the script's own PID and $! the PID of the last background command (lesson 139). The sleep is a child of the script (its PPID is the script's PID), and, surprisingly, it is in the same process group, marked +. The reason is that job control, the feature that gives each job its own process group, is turned off by default in scripts. In a non-interactive shell, & means only "do not wait"; the terminal still considers the job part of the foreground. To protect such jobs from Ctrl + C, Bash makes background commands in a non-interactive shell ignore SIGINT (lesson 87 observed this).
set -m turns job control on in a script. The same test with set -m at the top:
PID PPID PGID TPGID STAT COMMAND
937 935 937 939 Ss bash
938 937 938 939 S sleep
Now the sleep has its own group (938). The TPGID column shows the terminal's foreground group, 939, which belonged to the ps command itself while it ran; neither the script nor the sleep has a +. Interactive shells have job control on automatically, so every command line you type there becomes its own job with its own process group.
Without a terminal at all (for example in a cron job or with output piped to a file), there is no foreground group, and ps shows no + anywhere.
Job Control in an Interactive Shell
In an interactive shell, job control lets you move work between the foreground and the background. The session below was run in a real terminal session (provided by script); the prompt is shown as $, and ^Z and ^C mark where Ctrl + Z and Ctrl + C were pressed:
$ sleep 30
^Z
[1]+ Stopped sleep 30
$ jobs
[1]+ Stopped sleep 30
$ bg
[1]+ sleep 30 &
$ jobs
[1]+ Running sleep 30 &
$ sleep 40 &
[2] 975
$ jobs -l
[1]- 969 Running sleep 30 &
[2]+ 975 Running sleep 40 &
$ fg %1
sleep 30
^C
$ jobs
[2]+ Running sleep 40 &
$ kill %2
$ jobs
[2]+ Terminated sleep 40
Step by step:
sleep 30ran in the foreground. Ctrl + Z sent it SIGTSTP, which stopped (paused) it, and the shell got the terminal back. The job is still alive, just frozen.jobslists the shell's jobs.[1]is the job number, which is local to this shell and different from the PID.bgresumed the stopped job in the background. It continues counting down while the shell accepts new commands.sleep 40 &started a second job directly in the background. An interactive shell prints the job number and the PID, here[2] 975.jobs -ladds the PIDs to the list. The+marks the current job (the default forfgandbg), the-the previous one.fg %1brought job 1 back to the foreground. Because it now owned the terminal, Ctrl + C reached it and ended it.kill %2sent SIGTERM to job 2.%2is a job specification, whichkill,fg,bgandwaitunderstand in a shell with job control. The shell reports that the job was terminated at the next opportunity.
Lesson 137 covers these commands in detail.
Background Jobs and the Keyboard
Only the foreground group may read from the terminal. When a background job tries, the terminal sends it SIGTTIN, which stops it:
$ cat &
[1] 990
$ jobs
[1]+ Stopped cat
cat without arguments reads from the keyboard, so as a background job it was stopped immediately. fg would bring it to the foreground, where it can read normally. This rule prevents a background job and the shell from fighting over every key you type.
Writing to the terminal is allowed by default, so output from background jobs appears wherever the cursor happens to be, mixed with other output:
( for i in 1 2 3; do echo " job: line $i"; sleep 0.3; done ) &
for i in 1 2 3; do echo "main: line $i"; sleep 0.3; done
wait
main: line 1
job: line 1
job: line 2
main: line 2
main: line 3
job: line 3
The exact order depends on timing and changed between runs. In a terminal, background output can also appear in the middle of the line you are typing. A background job whose output matters should write to a file (cmd > out.log 2>&1 &). The terminal setting stty tostop makes background jobs stop when they try to write as well; it is off on most systems.
Background Jobs in Scripts
In a script (a non-interactive shell without job control), background commands behave a little differently:
Standard input becomes /dev/null. POSIX requires this for background commands when job control is off, so that they cannot steal the script's input. A background cat therefore reads nothing, unless its input is redirected explicitly:
printf 'hello\n' | bash -c 'cat > bg.txt & wait; echo "background cat read $(wc -c < bg.txt) bytes"'
printf 'hello\n' | bash -c 'cat > bg2.txt <&0 & wait; echo "with <&0: $(wc -c < bg2.txt) bytes"'
background cat read 0 bytes
with <&0: 6 bytes
Dash gave the same 0 bytes. With set -m, Bash did not redirect the input either, and cat read all 6 bytes; it also printed the job-done line [1]+ Done cat > bg3.txt, as an interactive shell does.
No job messages are printed. A script does not print [1] 975 or Done lines, which keeps its output clean.
Background jobs outlive the script. When a script ends, its background commands keep running. They become orphans and are adopted by process 1:
$ bash -c 'sleep 5 & echo "script started sleep as $!"; echo "script ends"'
script started sleep as 1003
script ends
$ ps -o pid,ppid,stat,comm -p 1003
PID PPID STAT COMMAND
1003 1 S sleep
The PPID is now 1. This is occasionally intended (a script that starts a long-running service), but usually it means the script forgot to wait. A script that starts background work should wait for it before it ends, so that its exit status and timing reflect all of the work. Lesson 124 showed cleanup with kill and wait in an EXIT trap for the case where the script ends early.
Leaving the Shell While Jobs Exist
An interactive shell protects stopped jobs from being forgotten. The first exit prints a warning instead of exiting:
$ sleep 50
^Z
[2]+ Stopped sleep 50
$ exit
exit
There are stopped jobs.
According to the Bash manual, a second exit immediately afterwards (with no other command in between) exits anyway and terminates the stopped jobs. In the test, running jobs between the two attempts made the warning appear again; two exit commands in a row then ended the shell, and afterwards neither the stopped cat nor the stopped sleep was still running.
Running background jobs are not mentioned by exit. What happens to them depends on how the shell ends. When the terminal window is closed, the shell receives SIGHUP ("hangup") and sends SIGHUP to its jobs, which normally ends them. (This part was not tested, because it needs a real terminal window; it is described in the Bash manual, as is the huponexit option, which makes a plain exit of a login shell send SIGHUP too.) Two tools keep a command running after you leave:
nohup command &starts the command with SIGHUP ignored. If its output would go to the terminal,nohupappends it to the filenohup.outinstead:
$ nohup sleep 1 &
[3] 998
$ nohup: ignoring input and appending output to 'nohup.out'
The message appeared after the next prompt, which is typical of background output.
disownremoves a job from the shell's job table, so the shell does not send it SIGHUP and no longer lists it:
$ sleep 60 &
[1] 1027
$ disown
$ jobs
$ echo "still running: $(pgrep -c -f "sleep 60")"
still running: 1
For work that must survive logouts and reboots reliably, a terminal multiplexer such as tmux or screen, or a proper service manager such as systemd, is a better tool than nohup.
A Complete Example
pgzip.sh compresses several files with gzip, either all at once in the background or, with -s, one after another. It shows the practical reason to use background processes: independent work finishes sooner when it runs side by side, up to the number of CPUs available.
#!/usr/bin/env bash
# pgzip.sh [-s] FILE...: compress FILEs with gzip, all at once in the background
# (or one after another with -s), and report the time taken.
set -uo pipefail
prog=${0##*/}
sequential=0
if [[ ${1-} == -s ]]; then sequential=1; shift; fi
(( $# > 0 )) || { echo "usage: $prog [-s] FILE..." >&2; exit 2; }
now_ms() { local t=${EPOCHREALTIME/./}; echo $(( t / 1000 )); } # Bash 5.0+
secs() { printf '%d.%01ds' $(( $1 / 1000 )) $(( $1 % 1000 / 100 )); }
compress() { # compress FILE: one job, reports its own time
local file=$1 start
start=$(now_ms)
if gzip -9 -k -f -- "$file"; then
printf ' done %-12s %s\n' "$file" "$(secs $(( $(now_ms) - start )))"
else
printf ' FAILED %s\n' "$file" >&2
return 1
fi
}
begin=$(now_ms)
pids=() failed=0
for f in "$@"; do
if (( sequential )); then
compress "$f" || failed=$((failed + 1))
else
compress "$f" & # start the job and move on at once
pids+=("$!")
printf ' started %-12s PID %d\n' "$f" "$!"
fi
done
for pid in "${pids[@]}"; do # wait for every job and collect its status
wait "$pid" || failed=$((failed + 1))
done
printf '%d file(s), %d failed, %s in total (%s)\n' "$#" "$failed" \
"$(secs $(( $(now_ms) - begin )))" \
"$( (( sequential )) && echo one after another || echo in the background)"
(( failed == 0 ))
How It Works
compressis an ordinary function. Called normally, it runs in the foreground; followed by&, Bash runs it in a background child process. The same code serves both modes.$!holds the PID of the job just started (lesson 139). The script collects the PIDs in an array.wait "$pid"waits for one particular job and returns that job's exit status, which is how the script counts failures even though the jobs ran in the background (lesson 138 coverswaitin detail). In sequential mode, thepidsarray stays empty and the waiting loop does nothing.EPOCHREALTIME(Bash 5.0 and later) holds the current time in seconds with microseconds, such as1795350000.123456. Removing the dot gives microseconds as an integer, so Bash can subtract times without floating-point arithmetic. This assumes a locale that uses a dot as the decimal separator, as the C locale does.- Output order: each background job prints its own
doneline when it finishes, so those lines appear in the order the jobs finished, not the order they were started. - The last line,
(( failed == 0 )), sets the script's exit status: 0 if everything succeeded, 1 otherwise.set -eis not used, because the script handles each failure itself.
Running the Complete Example
Four test files of about 23 MB each (seq 1 3000000 > a.log, and the same for b, c and d) were compressed on a machine with 2 CPUs (nproc printed 2). One after another:
$ bash pgzip.sh -s a.log b.log c.log d.log
done a.log 1.5s
done b.log 1.5s
done c.log 1.5s
done d.log 1.5s
4 file(s), 0 failed, 6.1s in total (one after another)
All four in the background:
$ bash pgzip.sh a.log b.log c.log d.log
started a.log PID 1097
started b.log PID 1098
started c.log PID 1100
started d.log PID 1101
done a.log 3.1s
done c.log 3.2s
done d.log 3.2s
done b.log 3.2s
4 file(s), 0 failed, 3.2s in total (in the background)
The total time halved, but each individual job took about twice as long (3.1 instead of 1.5 seconds). Compressing is CPU work, and four jobs had to share two CPUs, so the best possible speed-up was two. With only two files, each job had a CPU to itself:
$ bash pgzip.sh a.log b.log
started a.log PID 1122
started b.log PID 1123
done a.log 1.5s
done b.log 1.6s
2 file(s), 0 failed, 1.6s in total (in the background)
Starting many more jobs than there are CPUs does not make CPU-bound work faster; it only adds switching overhead and memory use. Jobs that mostly wait (for the network or a slow disk) are different, and can benefit from more parallelism than the CPU count.
A failing job does not stop the others, and its status is still collected:
$ bash pgzip.sh a.log missing.log
started a.log PID 1137
started missing.log PID 1138
gzip: missing.log: No such file or directory
FAILED missing.log
done a.log 1.5s
2 file(s), 1 failed, 1.5s in total (in the background)
The exit status was 1. The PIDs and times will differ on your machine, and the order of the done lines can change from run to run. gzip -k keeps the original files, so a.log.gz (about 6.4 MB) sits next to a.log, and gzip -t a.log.gz confirmed that the archive is valid.