🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Job Control

Job control runs commands in the background so a script can do other work while they finish. The wait command pauses the script until a background job is done.

One background job, finished with wait

The background job prints its line after a short pause. The wait command holds the script until that line appears.

echo "main starts"
(sleep 0.1; echo "background job done") &
wait
echo "main done"

List a running job with jobs

The sleep command is still running when jobs lists it. The wait command then holds the script until the job finishes.

sleep 0.2 &
jobs
wait
echo "waited"

The main script continues while a job runs

The main script prints its line at once, without waiting for the slow job. The wait command then holds it until the job prints its own line.

(sleep 0.2; echo "slow job done") &
echo "main continues at once"
wait
echo "main waited for the job"

Example

(sleep 0.1; echo "backup done" > backup.txt) &
(sleep 0.1; echo "report done" > report.txt) &
wait
cat backup.txt
cat report.txt
echo "all jobs finished"

Key points

  • &: starts a command as a background job and lets the script continue.
  • jobs: lists the background jobs that are still running.
  • wait: pauses until every background job has finished.
  • fg and bg: interactive-shell commands that move jobs between foreground and background.
  • A script is non-interactive, so it uses jobs and wait instead of fg and bg.
  • Every background job must finish inside the script: call wait before the end.

In this example, two background jobs start at once, and each writes its result to its own file. The wait command holds the script until both jobs have finished. The two cat commands then print the results in a fixed order. The last line confirms that every job is done.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does wait do in a script?