Error Handling and Defensive Scripting

Report what failed, preserve good results, and test recovery.

A failure policy is part of the interface

if data=$(collect_fixture 2> errors.txt); then
  printf 'collection complete\n'
else
  status=$?
  printf 'collection failed status=%s\n' "$status"
fi

Use the lesson's producer returning 6. Capture status before printing. Negating the condition with ! changes the status observed in the branch.

Shell options are not a blanket guarantee

Mechanism Boundary
set -e Conditional and other exceptions matter
set -u An empty variable is still set
pipefail Partial files remain; process substitutions are separate
Explicit checks Must follow the actual command contract

The lesson runs option experiments in child shells and verifies both unguarded failure and a handled if condition.

Cleanup has a scope and a limit

Create a unique owned directory, register EXIT cleanup, and preserve the original exit status.

The fixture exits 7; the parent observes 7 and verifies that directory is gone. A separate TERM case observes 143 and verifies cleanup.

EXIT cleanup cannot run after SIGKILL or machine failure. Never use a shared or unvalidated path as a recursive cleanup target.

Different checks answer different questions

Check Evidence
bash -n Script parses
bash -x Expanded commands in this execution
ShellCheck Suspicious static patterns
Behavioral tests Specified outputs and state for supplied cases

Traces can expose secrets. Use synthetic inputs and review stderr before sharing.

Correct the quote, then test behavior

printf '<%s>\n' "$1"

The unquoted variant triggers SC2086. The corrected fixture passes syntax and static checks, then runs with a spaced label, literal wildcard, and empty argument.

Lint success does not establish operational correctness or authorize the input.

Keep commands and data separate

command_args=(printf '%s\n' 'label; printf injected')
"${command_args[@]}"

Expected: the literal text label; printf injected.

Do not feed assembled data through eval. Check dependencies with command -v and validate the properties the next operation actually requires.

Stage a report before publication

validate input -> owned staging directory -> checked copy
                                         -> same-filesystem rename

The publisher permits replacement of the chosen owned regular output. Missing input leaves a previous good report unchanged.

This is not a concurrent-writer lock, cross-filesystem transaction, or power-loss durability guarantee.

Test more than an exit code

Case Check
Success Exact content, stdout, status, mode
Missing input Diagnostic, nonzero status, old output preserved
Wrong count Usage status 2, no success output
Missing destination directory Refusal before publication
Recovery Valid run after failure; no staging leftovers

Then complete the graded lab on your VM. Record the limits of the test matrix rather than claiming exhaustive coverage.

Sources: ShellCheck documentation, Bash shell options, and Linuxize references linked in the lessons. Fixtures and contracts are original.