Running Commands in the Background with &

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 136 of 205

The & control operator tells Bash to start a command and not wait for it. The command runs in a separate child process while the shell immediately moves on to the next command, or, in an interactive shell, shows the next prompt. This is how a script runs several slow tasks at the same time, and how you keep a long-running program going in a terminal while you continue to work.

Lesson 135 explained what foreground and background processes are and how the terminal treats them. This lesson concentrates on the & operator itself: where it can appear, what exactly it puts in the background, what a background command can and cannot share with the shell that started it, and how to organize several background jobs in a script.

The Basic Form

Put & at the end of a command:

sleep 1 &
echo "started, status $?"
wait
started, status 0

Bash forks a child process for sleep 1, does not wait for it, and runs echo immediately. Three details are worth remembering from the start:

  • $? is 0 right after &. Starting a background command always counts as success, because the command has only just started. Its real exit status becomes available later through wait (lesson 138).
  • $! holds the process ID (PID) of the new job. Lesson 139 covers $! in detail.
  • wait pauses until the background jobs have finished. Without it, a script can reach its end while its jobs are still running.

The failing command below shows the difference between the status of & and the status of the job:

false &
echo "after false &: \$?=$?"
wait $!
echo "wait \$! gives $?"
after false &: $?=0
wait $! gives 1

& Is a Command Separator

Like ; and a newline, & ends a command. That means commands can follow it on the same line, and each & starts another job:

sleep 0.3 & echo "printed at once"
echo one & echo two & wait
printed at once
one
two

In the second line, both echo commands run as background jobs and wait runs in the foreground until they are done. The order of one and two depends on which job is scheduled first; it can differ between runs.

Because & already ends the command, it cannot be followed by ;:

sleep 0 &;
s1.sh: line 1: syntax error near unexpected token `;'
s1.sh: line 1: `sleep 0 &;'

The script stopped with status 2. Write sleep 0 & at the end of a line, or sleep 0 & next_command on one line. The same rule applies inside compound commands: if true; then sleep 1 & fi is correct, with no ; after the &.

What Exactly Goes to the Background

& applies to the whole list in front of it, back to the previous ;, & or newline. This matters when && or || is involved:

{ sleep 0.2; echo "first"; } && echo "second" &
echo "main goes on"
wait
main goes on
first
second

The entire { ...; } && echo "second" list ran in the background as one job, so main goes on appeared first. Bash did not run the group in the foreground and only echo "second" in the background. The Bash manual describes this precedence: && and || bind more tightly than ; and &.

The following forms are all valid background jobs:

FormWhat runs in the background
cmd &one simple command
cmd1 | cmd2 &the whole pipeline
a && b &the whole && list
{ cmd1; cmd2; } &a group of commands
( cmd1; cmd2 ) &a subshell (a child process either way)
myfunc arg &a shell function, in a child process
for ...; do ...; done &an entire loop

A pipeline in the background:

printf '3\n1\n2\n' | sort > sorted.txt &
wait
cat sorted.txt
1
2
3

A function in the background:

work() { sleep 0.3; echo "work $1 done"; }
work A & work B &
wait
work A done
work B done

Each call of work runs in its own child process, so both finish after about 0.3 seconds instead of 0.6. The two lines can appear in either order.

A Background Job Is a Separate Process

A background job, even a { } group or a function, runs in a copy of the shell. It starts with all the variables, functions and the current directory of the parent, but changes it makes stay in that copy:

count=0
{ count=5; echo "inside job: count=$count"; } &
wait
echo "after wait: count=$count"

( cd /tmp && echo "subshell job in $PWD" ) &
wait
echo "still in $PWD"
inside job: count=5
after wait: count=0
subshell job in /tmp
still in /home/ana/project

The parent's count is still 0 and its working directory did not change. This is the same rule that applies to pipelines and ( ) subshells (lessons 83 and 93), and it decides how background jobs must report results: through their exit status (collected with wait), through files, or through their output. The complete example at the end of this lesson uses one file per job.

Output and Input of Background Jobs

A background job inherits the standard output and standard error of the shell, so in a terminal its output appears wherever the cursor happens to be, mixed with other output. When a background job's output matters, redirect it:

{ echo out; echo err >&2; } > job.log 2>&1 &
wait
cat job.log
out
err

The redirections belong to the job and are written before &. long_task &> task.log & is the Bash short form of the same thing (lesson 60).

Standard input is different in scripts. As lesson 135 showed, when job control is off, which is the default in scripts, Bash connects a background command's standard input to /dev/null, so the job cannot consume input meant for the script. If a background job really should read the script's input, redirect it explicitly with < file or <&0.

Background Jobs in an Interactive Shell

At the prompt, Bash prints a line for each new job: the job number in brackets and the PID. When the job ends, it reports Done just before the next prompt. This session was run in a terminal:

$ sleep 2 &
[1] 290
$ sleep 0.5 & sleep 0.6 &
[2] 291
[3] 292
$ echo hi
hi
[1]   Done                    sleep 2
[2]-  Done                    sleep 0.5
[3]+  Done                    sleep 0.6
$

Bash does not interrupt you to say a job is done; it waits until it is about to print a prompt. Lesson 137 shows how to list, resume and move these jobs with jobs, fg and bg. Scripts print none of these lines.

Running Several Jobs at Once

The most common reason to use & in a script is to save time by running independent tasks in parallel. Starting jobs in a loop and waiting for all of them looks like this:

for d in 0.6 0.2 0.4; do
    { sleep "$d"; echo "slept $d"; } &
done
wait
slept 0.2
slept 0.4
slept 0.6

The jobs were started in the order 0.6, 0.2, 0.4, but their output appeared in the order they finished. Three one-second jobs started this way take about one second in total, not three:

start=$EPOCHREALTIME
for n in 1 2 3; do sleep 1 & done
wait
echo "three 1-second sleeps took $(( (${EPOCHREALTIME/./} - ${start/./}) / 100000 )) tenths"
three 1-second sleeps took 10 tenths

EPOCHREALTIME (Bash 5.0 and later) holds the current time in seconds with six decimal places. Removing the dot turns it into microseconds, and dividing by 100000 gives tenths of a second.

sleep does not use the CPU, so any number of sleeps can overlap. Real work is different. CPU-heavy jobs can only run truly in parallel up to the number of CPU cores (nproc prints it), and starting hundreds of jobs at once can exhaust memory or open files. A script therefore usually limits how many jobs run at the same time. The simplest way is to work in batches: start up to N jobs, wait for the batch, then start the next one. Lesson 138 shows a smoother method with wait -n, which starts a new job as soon as any running job finishes.

A Complete Example

checksums.sh computes SHA-256 checksums of several files in the background, at most N at a time (-j N, default 4), and prints the results in the order the files were given, even though the jobs finish in a different order.

#!/usr/bin/env bash
# checksums.sh [-j N] FILE...: SHA-256 checksums computed in the background,
# at most N at a time, printed in the order the files were given.
set -uo pipefail
prog=${0##*/}
max=4
if [[ ${1-} == -j ]]; then
    [[ ${2-} =~ ^[1-9][0-9]*$ ]] || { echo "$prog: -j needs a positive number" >&2; exit 2; }
    max=$2; shift 2
fi
(( $# > 0 )) || { echo "usage: $prog [-j N] FILE..." >&2; exit 2; }

results=$(mktemp -d) || exit 1
trap 'rm -rf -- "$results"' EXIT

checksum() {                       # checksum INDEX FILE: one background job
    local sum
    if sum=$(sha256sum < "$2"); then
        printf '%s  %s\n' "${sum%% *}" "$2" > "$results/$1"
    else
        printf 'FAILED  %s\n' "$2" > "$results/$1"
        return 1
    fi
}

i=0 running=0
for file in "$@"; do
    checksum "$i" "$file" &        # start the job; the loop continues at once
    i=$(( i + 1 )) running=$(( running + 1 ))
    if (( running == max )); then  # batch is full: let it finish
        wait
        running=0
    fi
done
wait                               # the last, possibly partial, batch

failed=0
for (( n = 0; n < i; n++ )); do
    cat "$results/$n"
    [[ $(< "$results/$n") == FAILED* ]] && failed=$(( failed + 1 ))
done
(( failed == 0 )) || { echo "$prog: $failed file(s) could not be read" >&2; exit 1; }

How It Works

  • checksum "$i" "$file" & runs the function as a background job. Because a job cannot set variables in the parent, each job writes its result to its own file, named after the file's position in the argument list (0, 1, 2, ...). A temporary directory from mktemp -d holds these files, and the EXIT trap removes it (lessons 113 and 124).
  • The batch counter running counts jobs started since the last wait. When it reaches max, the script waits for the whole batch before starting more. After the loop, a final wait collects the last batch, which may be smaller.
  • Ordered output: the final loop reads the result files in index order, so the output follows the argument order no matter which job finished first.
  • sha256sum < "$2" reads the file through a redirection. When the file cannot be opened, the redirection fails, Bash prints the error, and sha256sum does not run, so the if takes the else branch. ${sum%% *} keeps only the hash, removing the - that sha256sum prints for standard input.
  • Failures are recorded as FAILED lines and counted from the result files, not from wait, because a plain wait without arguments always returns 0. Lesson 138 shows how to collect each job's exit status with wait PID.

Running the Complete Example

Three small text files, one of them with a space in its name:

$ bash checksums.sh -j 2 todo.txt notes.txt "my file.txt"
409baa381eaebfc8c71676ecb0eed6659ea7510b4b42f101b152c7f0696150c5  todo.txt
ed43fbd9937617ab4c32ca7917e1844caec421f5e151eb09d701bd4708979377  notes.txt
c73b73af8851e9e91bc6b4dc12e7dace0a2bfb931c1d0b8b36ef367319f58cd1  my file.txt

A missing file in the middle:

$ bash checksums.sh -j 2 todo.txt missing.txt notes.txt
checksums.sh: line 18: missing.txt: No such file or directory
409baa381eaebfc8c71676ecb0eed6659ea7510b4b42f101b152c7f0696150c5  todo.txt
FAILED  missing.txt
ed43fbd9937617ab4c32ca7917e1844caec421f5e151eb09d701bd4708979377  notes.txt
checksums.sh: 1 file(s) could not be read

The exit status was 1. The error message appeared first because the job printed it while running, before the script printed the collected results. Invalid input is rejected with status 2:

$ bash checksums.sh -j 0 a.bin
checksums.sh: -j needs a positive number
$ bash checksums.sh
usage: checksums.sh [-j N] FILE...

To see the time saved, four files of 250 MB of random data each were checksummed on a machine with 2 CPU cores:

CommandTime
bash checksums.sh -j 1 a.bin b.bin c.bin d.bin0.8 s
bash checksums.sh -j 2 a.bin b.bin c.bin d.bin0.4 s
bash checksums.sh a.bin b.bin c.bin d.bin (4 at a time)0.4 s

With -j 1 the files were processed one after another. Two jobs at a time halved the time, and four at a time was no faster, because two cores can only run two checksum calculations at once. Your times will differ with the disk, the CPU and the file sizes.

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 Running Commands in the Background with & and get answers drawn from it.

Signed-in readers only.