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
mktemp -dmakes a directory only this run knows.- The
trap ... EXITremoves it on any exit path. - Work inside is free to create and copy without fear.
Keywords and builtins used here
echoprintftrap
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.
Step 3 of 3 in Scripts & safety, step 24 of 26 in Language basics.