Background Processes in Shell

Level 4120 keystrokes

& starts a function in the background so the script keeps going, $! gives that job's PID, and wait pauses until it finishes. The PID in the output varies.

Shell code

# A slow task: waits 5 seconds, then prints Done!
1long_task() { sleep 5; echo "Done!"; }
# & runs it in the background; the script continues at once
2long_task &
# $! is the PID of the most recent background job
3pid=$!
# Printed right away, before Done!; the PID varies
4echo "Started process $pid"
# Block until that process finishes
5wait $pid
# Runs only after the background task is done
6echo "Process completed"

Output

Started process 12345
Done!
Process completed
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 6
  • $× 3
  • _× 2
  • ;× 2
  • !× 2
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • &× 1

More Shell examples at level 4

← Shell typing practice