🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Advanced Introduction

Bash Advanced scripting is the practice of coordinating several processes from one script. Each process keeps its own state, so the script must control starts, waits, and endings.

Background workers plus wait

Two background workers each write one file. wait holds the script until both finish, then cat reads the files in a fixed order.

( printf 'alpha done\n' > worker-a.txt ) &
( printf 'beta done\n' > worker-b.txt ) &
wait
cat worker-a.txt worker-b.txt

Every pipeline stage has its own status

PIPESTATUS holds one exit status per pipeline stage, in stage order. The three numbers show exactly which stages failed.

false | true | false
echo "stages: ${PIPESTATUS[0]} ${PIPESTATUS[1]} ${PIPESTATUS[2]}"

pipefail exposes a hidden failure

Without pipefail, a pipeline reports only its last stage. With pipefail set, the same pipeline reports the failure in its first stage.

set -o pipefail
false | true
echo "pipe status: $?"

Example

( printf 'part one\n' > part-a.txt ) &
( printf 'part two\n' > part-b.txt ) &
wait
cat part-a.txt part-b.txt
printf 'total: 42\n' | grep 'total'
echo "check status: ${PIPESTATUS[0]} ${PIPESTATUS[1]}"

Key points

  • Coordination: one script can start workers, collect their results, and stop them cleanly.
  • Waiting: wait collects a finished job, and wait -n collects whichever job finishes first.
  • Two-way channels: a coprocess exchanges messages with the script in both directions.
  • Named pipes: a FIFO lets two commands pass data through a filesystem name.
  • Groups: a process group lets one signal reach a job and all its children.
  • Honest limits: timing between processes is never exact, so scripts must prove completion with files or exit statuses, not sleeps.

In this example, two background workers each write one part file. wait pauses the script until both workers finish. cat reads the parts in a fixed order, so the output order never depends on which worker finished first. A short pipeline then checks its own stages with PIPESTATUS.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script starts two background workers that write separate files. Why must it call wait before reading the files?