Cleaning up with trap
- Version
- 5.3
- Review
- Draft
Summary#
Install an EXIT trap to clean up resources when the shell exits. Register it immediately after acquiring the resource so the cleanup also runs when later work exits with a failure.
Syntax#
trap 'cleanup' EXIT
trap -p EXIT # Print the current handler
trap - EXIT # Clear the handler
Example#
This example runs offline and needs mktemp and rm, both supplied by BusyBox in the official Bash 5.3 image. Each worker uses a freshly created temporary directory. The caller checks that cleanup ran after both success and a deliberate failure.
(
for requested_status in 0 7; do
scratch=$(mktemp -d) || exit 1
status=0
(
trap 'rm -rf -- "$scratch"' EXIT
printf '%s\n' 'report in progress' > "$scratch/report" || exit 1
exit "$requested_status"
) || status=$?
if [[ -e $scratch ]]; then
printf '%s\n' 'scratch directory still exists' >&2
exit 1
fi
printf 'worker status %d, scratch removed\n' "$status"
done
)
Expected output#
worker status 0, scratch removed
worker status 7, scratch removed
Common mistakes#
Use a single-quoted trap action so $scratch is expanded when the trap runs. Keep that variable pointed at the directory you created. Registering a new action for EXIT replaces the previous one, so put related cleanup steps in one handler. To handle TERM explicitly, a separate TERM handler can call exit to trigger the same cleanup.
Version applicability#
The EXIT handler and the inspection and reset forms shown here work on Bash 3.2. The complete example also needs a mktemp that accepts -d with its default template and an rm that accepts --. The randomly generated directory name is omitted from the output.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0