TRAP Cleanup Exit Error Handling
Guarantee resource cleanup on any exit path with traps for EXIT INT TERM, keeping partial work dirs off the filesystem.
Code
#!/usr/bin/env bash
set -euo pipefail
WORKDIR=""
FINISHED=false
cleanup() {
local exit_code=$?
if [[ "$FINISHED" == false && -n "$WORKDIR" && -d "$WORKDIR" ]]; then
rm -rf "$WORKDIR"
echo "Error: 未完成的工作目录已清理: ${WORKDIR}" >&2
fi
echo "cleanup done, exit ${exit_code}"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
die() {
echo "Error: $*" >&2
exit 1
}
convert_dataset() {
WORKDIR=$(mktemp -d) || die "无法创建临时目录"
local input="$1"
gzip -dc "$input" > "$WORKDIR/raw.json" \
|| die "解压失败: ${input}"
jq -c '.[]' "$WORKDIR/raw.json" > "$WORKDIR/records.ndjson" \
|| die "JSON 转换失败"
wc -l < "$WORKDIR/records.ndjson"
}
main() {
[[ -f "$1" ]] || die "输入文件不存在: ${1}"
local lines
lines=$(convert_dataset "$1")
echo "converted ${lines} records"
FINISHED=true # 成功路径:保留产物目录给调用方
mv "$WORKDIR/records.ndjson" ./out.ndjson
}
main "$@"
What the code does
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to rm, trap, gzip, jq and wc, chained through 8 pipes so each stage’s output feeds the next.
4 helper functions (cleanup, die, convert_dataset and main) keep the repeated logic out of the main flow.
A trap handles termination signals so temporary state is cleaned up even on early exit.
Caveats
- The pipeline is 8 stages deep — when it misbehaves, split the pipe and test the stages separately.
The key statements that remain
WORKDIR=$(mktemp -d) || die "无法创建临时目录"
gzip -dc "$input" > "$WORKDIR/raw.json" \
|| die "解压失败: ${input}"
jq -c '.[]' "$WORKDIR/raw.json" > "$WORKDIR/records.ndjson" \
|| die "JSON 转换失败"
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `rm`, `trap`, `gzip`, `jq`, `wc` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.