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 "$@"
Report a problem with this exampleOpens a pre-filled issue on GitHub.