AdvancedLesson 13 of 15
Processes, Jobs, Signals & trap – Bash
Background jobs, parallel execution, catching signals and cleaning up properly.
An & at the end starts a command in the background. $! is the PID of the last background process, wait waits for child processes, jobs lists the shell's jobs. This is how you parallelize slow tasks:
sleep 2 & # starts in the background
echo "PID: $!"
jobs # [1]+ Running sleep 2 &
wait # waits for all background jobs
# check several URLs in parallel, then wait
for host in example.com example.org; do
( ping -c 1 "$host" > /dev/null && echo "$host ok" || echo "$host down" ) &
done
wait
echo "all done"Signals are messages to processes: SIGINT (Ctrl+C), SIGTERM (polite termination, default of kill), SIGKILL (kill -9, cannot be caught), SIGHUP. With trap you react to them in scripts. The pseudo-signal EXIT fires when the shell exits – in any way.
#!/usr/bin/env bash
tmp=$(mktemp)
aufraeumen() {
echo "Cleaning up ..."
rm -f "$tmp"
}
trap aufraeumen EXIT # always on exit
trap 'echo "Aborted by user"; exit 130' INT TERM
echo "working with $tmp"
sleep 30 # now press Ctrl+C -> output and cleanupWith nohup, disown or tmux/screen, processes keep running when the terminal is closed. Subshells ( ... ) have their own variables and cd; { ...; } runs in the current shell:
( cd /tmp && pwd ) # /tmp – your folder stays unchanged
pwd
x=1; ( x=2 ); echo "$x" # 1 the change in the subshell is gone
x=1; { x=2; }; echo "$x" # 2
nohup ./langer-job.sh > job.log 2>&1 & # survives closing the terminal
kill "$!" # terminate politely (SIGTERM)WarningWhen parallelizing in loops: without
wait the script may end before its child processes, and wait returns only the exit code of the last job waited for (wait $pid per PID gives individual codes). For many jobs with a limit, xargs -P N or GNU parallel is cleaner than a home-made pool.Tip
trap ... ERR (with set -E) can print the line number on every error: trap 'echo "Error in line $LINENO" >&2' ERR. This is worth its weight in gold when debugging CI scripts.