Write a shell script that cleans up after failure

8 steps · about 2 h 28 min · Intermediate

  1. 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.

  2. Validate and quote inputs (reference, GNU Bash manual, 24 min)

    Reject missing values and expand parameters without unintended word splitting or pathname expansion.

  3. 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.

  4. Create a private temporary workspace (reference, GNU Coreutils manual, 14 min)

    Avoid predictable names, races and collisions with another process's files.

  5. Register cleanup traps (reference, GNU Bash manual, 18 min)

    Remove owned temporary resources on normal exit and common termination signals.

  6. Preserve meaningful exit status (reference, GNU Bash manual, 14 min)

    Return the operation's result even when cleanup commands also run and can fail.

  7. Check the script statically (guide, ShellCheck, 18 min)

    Catch quoting, test-expression and portability mistakes before exercising destructive-looking paths.

  8. 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.