Running Commands in the Background (&) and $!
In this page:
Starting a Background Job
Appending & after a command launches it asynchronously; the shell does not wait for it and immediately continues to the next line. This lets independent tasks run concurrently.
Example: Starting a Background Job
#!/bin/bash
sleep 0.2 &
echo "this prints immediately, before the sleep finishes"
wait
echo "the background sleep has now finished"
Login to try C/C++/Java/PHP code in the editor
Capturing the Background PID with $!
$! expands to the process ID of the most recently started background job, which lets a script track, wait for, or send signals to that specific process later.
Example: Capturing the Background PID with $!
#!/bin/bash
sleep 0.2 &
pid=$!
echo "started background job with PID $pid"
wait "$pid"
echo "job $pid has completed"
Login to try C/C++/Java/PHP code in the editor
Running Several Jobs Concurrently
Multiple commands can be backgrounded one after another; each keeps its own PID in $! at the moment it starts, so PIDs must be saved into separate variables (or an array) if you want to reference them individually later.
Example: Running Several Jobs Concurrently
#!/bin/bash
sleep 0.1 &
pid1=$!
sleep 0.1 &
pid2=$!
echo "started jobs $pid1 and $pid2"
wait "$pid1" "$pid2"
echo "both jobs finished"
Login to try C/C++/Java/PHP code in the editor
- Assuming a backgrounded command's output won't interleave with the rest of the script's output; both run concurrently and can print at overlapping times.
- Forgetting
$!must be captured immediately after the&command, since it always refers to the most recently backgrounded job's PID. - Not waiting for background jobs before the script ends, which in an interactive shell is fine but can mean a non-interactive script exits before the job's work (like a file write) is actually done.
- Appending
&to a command starts it in the background and returns control immediately. $!holds the process ID (PID) of the most recently started background job.- Multiple
&jobs can run concurrently; usewaitto block until they finish. - Non-interactive scripts have job control disabled, so interactive builtins like
fg/bg/jobsare unreliable there;$!andwaitare the portable way to manage background work.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: