$_ CLI In Depth
Learning progress 0%
lesson robustness traps debugging

Temporary Files with mktemp

4 min read Module 15: Robust Scripts, Traps & Debugging Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:11

The problem with fixed names

A fixed path such as /tmp/work.txt has three problems. Two runs of the same script at the same time share the file. A stale file from an earlier crash can contaminate the new run. And in a directory that everybody can write to, another user can create the file first and make the script read or write data it should not touch. Predictable names in shared temporary space are a classic security bug.

BASH2 lines
echo "data" > /tmp/work.txt
cat /tmp/work.txt

This works on a single run, but the file name is the same on every run. A second user on a shared machine who knows the name can create that file first, and then your script writes to the file they chose, or they may replace it with a link to a file you did not mean to touch. The fix is not to pick a more complicated name by hand. It is to let the system create the name for you.

Creating a temporary file

mktemp creates a file with a unique name and prints the name. The file is created with permissions that only the owner can read and write, which is mode 600. If you give it a template, the trailing run of X characters is replaced by random characters. The template should include a readable prefix so that a leftover file is easy to recognize.

BASH3 lines
f=$(mktemp /tmp/report.XXXXXX)
echo "created: $f"
ls -l "$f"

The first line prints a path such as /tmp/report.a1B2c3, with random characters in place of the Xs. The listing shows the file belongs to you and has permissions that only you can read and write. The exact name differs on every run, so do not write scripts that expect a particular value.

Creating a temporary directory

The -d option creates a directory instead of a file. Use it when a step writes several files, such as a build that unpacks an archive. The directory is also created with mode 700, so only your user can enter it.

BASH4 lines
d=$(mktemp -d /tmp/build.XXXXXX)
echo "hello" > "$d/note.txt"
cat "$d/note.txt"
rm -rf "$d"

The script prints hello and then removes the whole directory. Always quote the variable in removal commands. A directory name with a space that is unquoted would be split, and rm -rf on the wrong words is one of the most damaging mistakes a shell can make.

Warning

Never run rm -rf on a variable that might be empty. Combine this unit with the strict mode unit: set -u stops the script on an unset name, and a check such as [[ -n $d ]] protects against an empty value that is set.

Combining mktemp with a trap

A temporary file is only useful if it is removed when the script ends, including when it fails. The pattern that solves this is to create the file, then register a trap that removes it, as the previous unit showed. Put both lines together, so that no path through the script can skip the cleanup.

BASH4 lines
tmp=$(mktemp /tmp/job.XXXXXX)
trap 'rm -f "$tmp"' EXIT
echo "step one" > "$tmp"
cat "$tmp"

The output is step one, and the file is removed when the script exits. The trap string uses single quotes so that the variable is read when the trap runs.

Where mktemp puts files

When the template has no directory part, mktemp uses the directory named by the TMPDIR environment variable, and falls back to /tmp. That lets users redirect scratch space with one variable. A template that includes a directory, as in the examples above, always uses that directory.

Hands-on: make a temporary file

Run the block below. It creates a file, shows its permissions, and removes it. Notice that the permissions are the same no matter where the file is created.

BASH3 lines
t=$(mktemp /tmp/demo.XXXXXX)
stat -c "%a %n" "$t"
rm -f "$t"

The output is the mode 600 followed by the path. The lab for this unit asks you to write a script that creates a temporary directory and removes it on exit, and it checks that the directory is gone.

set -e exceptions and trap cleanup

Visualizer

set -e stops a script when a command fails, but it skips a few contexts. A trap runs cleanup on exit, and the order of EXIT, ERR and INT decides what runs when.

1 / 6
contextset -e effect
plain failing commandexits the shell
if or while conditiondoes not exit
left side of && or ||does not exit; the command after the last operator still does
command negated with !does not exit
function body, when f runs in such a contextdoes not exit

set -e ends the shell when a command fails. The rows below are the exceptions; the first row is the default rule.

bash -c 'set -e; if false; then echo no; fi; echo "after if"; false || echo "after ||"; ! false; echo "after !"; f() { false; echo "inside f"; }; f || echo "f failed"; false; echo "never printed"'
Terminal lab · 2 steps · real Linux in your browser

Make temporary files safely

Create a temporary file with mktemp and a temporary directory that a trap removes.

01
Create a temporary file
Create mk.sh in /workspace. It creates a temporary file whose template is /workspace/scratch.XXXXXX, and it writes the file name into /workspace/made.txt: ``bash cat > mk.sh <<'EOF' #!/bin/bash f=$(mktemp /workspace/scratch.XXXXXX) echo "$f" > /workspace/made.txt EOF `` Run it and look at the name in made.txt. The name is different on every run.
Show hint for step 1
The X characters in the template are replaced for you. Do not write a fixed name yourself.
02
Use a temporary directory with a trap
Create dir.sh in /workspace. It creates a temporary directory with the template /workspace/work.XXXXXX, registers a trap that removes it on exit, writes hello into a file inside it, and prints the directory name: ``bash cat > dir.sh <<'EOF' #!/bin/bash d=$(mktemp -d /workspace/work.XXXXXX) trap 'rm -rf "$d"' EXIT echo hello > "$d/note.txt" echo "$d" EOF `` Run it. The directory name is printed, and the directory must be gone afterward.
Show hint for step 2
Use mktemp -d for the directory. The trap must refer to the quoted variable so the whole path is removed.
Check yourself Question 1 of 4
Concept Check Permissions of a new temporary file recall

What permissions does mktemp give a new file by default?

Recap & Key Takeaways

Fixed names in shared temporary directories can collide or be planted by other users, so let mktemp choose a unique name.
mktemp creates the file or directory atomically with owner-only permissions, and mktemp -d makes a directory.
Pair every mktemp with a trap that removes it, and quote the path in every removal command.
Without a directory in the template, mktemp uses TMPDIR or /tmp.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue