Parallel Processing in Shell

Level 5146 keystrokes

Each file is compressed in its own background subshell, so the gzip runs happen in parallel, and wait blocks until all of them finish. The "Processing" lines may appear in a different order; jobs -l prints nothing because no jobs are left.

Shell code

# Files to compress
1files=(file1.txt file2.txt file3.txt)
2for f in "${files[@]}"; do
# ( ) groups the commands in a subshell; & runs it in the background
# gzip replaces each file with a compressed .gz file
3 (echo "Processing $f"; gzip "$f") &
4done
# wait with no arguments waits for all background jobs
5wait
# Printed after every gzip has finished
6echo "All files compressed"
# jobs -l lists jobs with their PIDs; here none are left, so it prints nothing
7jobs -l

Output

Processing file1.txt
Processing file2.txt
Processing file3.txt
All files compressed
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.

  • "× 8
  • .× 3
  • $× 3
  • ;× 2
  • (× 2
  • )× 2
  • -× 1
  • [× 1
  • ]× 1
  • {× 1

More Shell examples at level 5

← Shell typing practice