Foreground and Background Processes

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 135 of 205

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:

  1. sleep 30 ran 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.
  2. jobs lists the shell's jobs. [1] is the job number, which is local to this shell and different from the PID.
  3. bg resumed the stopped job in the background. It continues counting down while the shell accepts new commands.
  4. sleep 40 & started a second job directly in the background. An interactive shell prints the job number and the PID, here [2] 975. jobs -l adds the PIDs to the list. The + marks the current job (the default for fg and bg), the - the previous one.
  5. fg %1 brought job 1 back to the foreground. Because it now owned the terminal, Ctrl + C reached it and ended it.
  6. kill %2 sent SIGTERM to job 2. %2 is a job specification, which kill, fg, bg and wait understand 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, nohup appends it to the file nohup.out instead:
$ 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.

  • disown removes 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

  • compress is 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 covers wait in detail). In sequential mode, the pids array stays empty and the waiting loop does nothing.
  • EPOCHREALTIME (Bash 5.0 and later) holds the current time in seconds with microseconds, such as 1795350000.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 done line 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 -e is 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Foreground and Background Processes and get answers drawn from it.

Signed-in readers only.