Running Commands in the Background with &
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 throughwait(lesson 138).$!holds the process ID (PID) of the new job. Lesson 139 covers$!in detail.waitpauses 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:
| Form | What 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 frommktemp -dholds these files, and the EXIT trap removes it (lessons 113 and 124).- The batch counter
runningcounts jobs started since the lastwait. When it reachesmax, the script waits for the whole batch before starting more. After the loop, a finalwaitcollects 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, andsha256sumdoes not run, so theiftakes theelsebranch.${sum%% *}keeps only the hash, removing the-thatsha256sumprints for standard input.- Failures are recorded as
FAILEDlines and counted from the result files, not fromwait, because a plainwaitwithout arguments always returns 0. Lesson 138 shows how to collect each job's exit status withwait 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:
| Command | Time |
|---|---|
bash checksums.sh -j 1 a.bin b.bin c.bin d.bin | 0.8 s |
bash checksums.sh -j 2 a.bin b.bin c.bin d.bin | 0.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.