Generate unpredictable temp files and directories safely from the shell. 10.04.2026 | reading time: 2 min Temporary files are everywhere on Linux; `mktemp` lets you create them safely from shell scripts and the command line, avoiding predictable names and race conditions. See it in action Quick demo: ``` $ mktemp /tmp/tmp.0Yxk3mQ8 ``` The command creates a new file with a unique name and prints that path so you can use it immediately. A reliable script pattern Create a private working directory, ensure cleanup even on error, and work inside it: ``` tmpdir=$(mktemp -d) trap 'rm -rf "$tmpdir"' EXIT echo "Working in $tmpdir" # perform work here, files created inside "$tmpdir" ``` This avoids leaving behind artifacts and prevents TOCTOU races when mktemp actually creates the file or directory. Options and sharp edges Useful flags include `-d` to make a directory, `--tmpdir` to choose another base directory, and `--suffix` to add an extension; do not use `-u` because it returns a name without creating it and reintroduces race conditions; created files are typically mode 0600 which limits access to the creator; note that BSD and BusyBox variants have different flags, so prefer portable patterns when writing cross-platform scripts. Where mktemp fits in `mktemp` is the shell-level tool to get a secure temporary pathname quickly, but you will also meet higher-level facilities such as language libraries (Python's tempfile), system-wide cleaners and policies (systemd-tmpfiles), and distribution utilities that manage /tmp lifecycle; choose the right level depending on whether you need a short-lived script file or coordinated system cleanup. Next steps Practice by refactoring scripts that create /tmp files to use `mktemp` and `trap` for cleanup, and then explore language-specific temp APIs for richer needs; deepen your Linux skills and consider formal certificates like CompTIA Linux+ or LPIC-1, with intensive exam preparation available at bitsandbytes.academy. Join Bits & Bytes Academy First class LINUX exam preparation. utilities scripting filesystem security