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.

BashSecurity Boundaries

Code

snippet
#!/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

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.