typestar

mktemp & trap in Bash

Private scratch space that cleans itself up.

# mktemp hands out a private scratch file or directory
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

echo "working in $work"
printf 'draft\n' > "$work/notes.txt"
cp "$work/notes.txt" "$work/notes.bak"

ls "$work" | sort
# no rm needed here: the trap cleans up on exit

How it works

  1. mktemp -d makes a directory only this run knows.
  2. The trap ... EXIT removes it on any exit path.
  3. Work inside is free to create and copy without fear.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
267
Tokens
48
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 34 seconds.

Type this snippet

Step 3 of 3 in Scripts & safety, step 24 of 26 in Language basics.

← Previous Next →