bhylu.com

Advertisements

Bash Traps and Cleanup

Register cleanup for resources the script actually owns.

How it works

A trap schedules shell code for a signal or event such as EXIT. Cleanup should operate only on resources created and owned by the current invocation. Validate the physical path of a generated directory before recursive removal, and avoid leaving a wildcard or unchecked environment path inside a trap. Cleanup failure should not silently turn an earlier failure into success.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

traps-cleanup.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
marker=created
cleanup_marker() { marker=cleaned; }
trap cleanup_marker EXIT
cleanup_marker
[[ $marker == cleaned ]] || exit 1
trap - EXIT
printf "Cleanup function checked; trap released deliberately\n"

Expected result

Cleanup function checked; trap released deliberately

This small body tests registration and deliberate release without deleting anything. File-based lesson downloads include the full guarded temporary-workspace cleanup, not only this toy marker. The review verifies that their temporary directories are removed and a neighbour sentinel remains. Traps are part of lifecycle design, not permission to clean arbitrary files.

Primary technical reference: Bash documentation.