mktemp
The command that safely creates a new, uniquely named temporary file, or with -d a directory, and prints its path.
In more detail
Names like /tmp/myscript.tmp can collide with another run or be hijacked by another user, while mktemp picks an unpredictable name and creates it only readable by you. Pair it with an EXIT trap that removes it.
Example
work="$(mktemp -d)"; trap 'rm -rf "$work"' EXITRelated terms
- temporary file — A file or directory a script creates for its own scratch work and should delete before it finishes.
- EXIT trap — A trap on the special name EXIT, whose handler runs whenever the shell exits: at the end, on exit, or when set -e stops it.
- trap builtin — The builtin that runs a command or function when the shell receives a signal or exits, used for cleanup.
Taught in
- trap, Cleanup And Temporary Files — Bash Scripting & Command Line Automation