Prerequisites and ownership rule

A temporary report directory should disappear on ordinary completion and handled failures, while the caller should still receive the original failure code. This example needs Bash and GNU utilities on Linux. Run it in a writable scratch directory. It creates its temporary directory there using a fixed report.XXXXXX template, and removes only the path returned by that allocation.

The script initializes its directory variable before installing traps. Cleanup checks for a nonempty path before calling rm. The exit trap is installed before allocation, so an allocation failure still has a defined cleanup path. No user-supplied path is passed to the recursive removal command. Keep that ownership rule when adapting the sample to a real report job.

Preserve the original result

The first command in cleanup saves the incoming status from $?. Subsequent commands cannot then overwrite the status the function intends to return. The function disables its own EXIT trap, attempts removal, and explicitly exits with the saved value. A removal failure gets a diagnostic, while this particular policy preserves the original work status.

The sample converts INT and TERM into exits 130 and 143, which then pass through the EXIT cleanup path. The term demonstration signals the script process itself, not another service. The script also has an explicit failure mode returning seven and an invalid-option mode returning two. These deliberate modes make failure behavior reproducible without relying on a real disk or report failure.

Run and interpret the demonstration

The ok mode writes two lines to a temporary input and prints its line count. Run the commands from a normal interactive shell without enabling errexit in the parent, so the parent can print the status after each intentional failure. The semicolon in those commands belongs to the demonstration shell and does not change the child script exit status being printed.

The implementation uses Bash-specific syntax, including [[ ]] and local. Invoke it with bash cleanup.sh rather than sh cleanup.sh. The temporary path is quoted everywhere it is expanded, and -- ends rm option parsing. A real job with several temporary resources can extend the cleanup function while continuing to save the original status first.

Edge cases and troubleshooting

The EXIT trap does not guarantee cleanup after SIGKILL, a machine crash or loss of the filesystem. The validation exercised normal exit, explicit failure, a handled TERM and invalid input; INT and uncatchable termination were not exercised. Long-running child processes also require a separate signal and process-management design.

If files remain, first check that the script ran under Bash and that the directory was allocated by this execution. Do not add a broad wildcard deletion to compensate for an unclear lifecycle. The current policy reports cleanup failure without changing the saved status; a production job may choose a different success-versus-cleanup-failure policy, but should state and test it explicitly.

Complete example

Save as cleanup.sh.

#!/usr/bin/env bash
set -euo pipefail
work_dir=''
cleanup() {
    local status=$?
    trap - EXIT
    if [[ -n "$work_dir" ]]; then
        rm -rf -- "$work_dir" || printf 'cleanup failed\n' >&2
    fi
    exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
work_dir=$(mktemp -d './report.XXXXXX')
printf 'alpha\nbeta\n' > "$work_dir/input"
case "${1:-ok}" in
    ok) wc -l < "$work_dir/input" ;;
    fail) exit 7 ;;
    term) kill -TERM "$$" ;;
    *) printf 'use ok, fail, or term\n' >&2; exit 2 ;;
esac

Run and expected output

bash cleanup.sh ok
bash cleanup.sh fail; printf "status=%s\n" "$?"
bash cleanup.sh term; printf "status=%s\n" "$?"
2
status=7
status=143

Primary references

Continue with Linux tutorials.