Mktemp Workspace With Trap Cleanup
Create an isolated temp workspace with mktemp -d and guarantee removal through an EXIT trap even when the script is interrupted.
Code
#!/usr/bin/env bash
set -euo pipefail
# 可预测的临时路径是符号链接攻击面;mktemp -d 返回唯一安全目录
WORKDIR="$(mktemp -d)"
cleanup() {
rm -rf -- "$WORKDIR"
}
trap cleanup EXIT
echo "working in $WORKDIR"
mkdir -p "$WORKDIR/staging"
printf 'payload\n' > "$WORKDIR/staging/input.txt"
# 中途失败也安全:set -e 触发退出 → EXIT trap → 目录被清理
grep -q payload "$WORKDIR/staging/input.txt"
echo "verified; cleanup runs on exit"How the snippet works
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to rm, trap, mkdir and grep, chained so each stage’s output feeds the next.
A helper function (cleanup) keeps the repeated logic out of the main flow.
A trap handles termination signals so temporary state is cleaned up even on early exit.
Key statements worth quoting
WORKDIR="$(mktemp -d)"
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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`, `mkdir`, `grep` 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.