Write a shell script that cleans up after failure
8 steps · about 2 h 28 min · Intermediate
- Establish the script boundary (guide, GNU Bash manual, 16 min)
Run a named program with explicit arguments rather than growing an unrepeatable interactive command history.
- Validate and quote inputs (reference, GNU Bash manual, 24 min)
Reject missing values and expand parameters without unintended word splitting or pathname expansion.
- Handle expected failure explicitly (reference, GNU Bash manual, 20 min)
Compose AND and OR command lists for operations that may legitimately fail and need a defined recovery path.
- Create a private temporary workspace (reference, GNU Coreutils manual, 14 min)
Avoid predictable names, races and collisions with another process's files.
- Register cleanup traps (reference, GNU Bash manual, 18 min)
Remove owned temporary resources on normal exit and common termination signals.
- Preserve meaningful exit status (reference, GNU Bash manual, 14 min)
Return the operation's result even when cleanup commands also run and can fail.
- Check the script statically (guide, ShellCheck, 18 min)
Catch quoting, test-expression and portability mistakes before exercising destructive-looking paths.
- Test success, failure and interruption (guide, bats-core project, 24 min)
Run the script in temporary fixtures and assert output, status and cleanup rather than testing against valuable files.