Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

A script launches 8 uploads in the background with `&` and then calls `wait`. Three uploads failed, but the script exits 0.

IntermediateTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → wait with no arguments waits for all children and returns 0, regardless of their exit statuses. set -e does not apply to background jobs.

Diagnose →

bash -c 'false & true & wait; echo "rc=$?"'       # rc=0

Fix → Record each PID and wait for them individually, counting failures:

pids=()
for f in "${files[@]}"; do
  upload "$f" & pids+=("$!")
done
failed=0
for pid in "${pids[@]}"; do
  wait "$pid" || failed=$((failed + 1))
done
(( failed == 0 )) || die "$failed of ${#pids[@]} uploads failed"

For bounded parallelism with proper exit codes, xargs -0 -P4 -n1 ./upload.sh returns 123 if any invocation failed.

Prevent → Never use a bare wait when the outcome matters; wait -n (Bash 4.3+) is useful for "fail fast on first error".

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps