Background Jobs
Run tasks concurrently with &, track PIDs, and wait for completion. In non-interactive shells, prefer wait over interactive fg/bg.
Starting and Waiting
Output
Click Run to execute your code
Note:
$! expands to the PID of the most recent background command.Pro Tip: Use descriptive logging including job IDs and timestamps.
Caution:
fg/bg require interactive job control; they are not available in many non-interactive environments.Common Mistakes
1) Losing track of PIDs
Store PIDs immediately after launching background tasks.
2) Not handling failures
Check $? after wait to detect job errors.
Exercise: Parallel Sleeps
Task: Start two sleep commands in the background and wait for both to complete.
Output
Click Run to execute your code
Show Solution
sleep 1 & pid1=$!; sleep 2 & pid2=$!; wait "$pid1" "$pid2"Summary
- Launch with
&, capture$!. - Use
waitto synchronize. - Be cautious with interactive job control in scripts.
What's Next?
Diagnose issues and trace execution in Debugging.
Enjoying these tutorials?