Temporary Files in Shell

Level 4150 keystrokes

mktemp creates a temporary file or directory with a unique random name, and a trap removes both when the script exits. The paths in the output vary on every run.

Shell code

# Create an empty temp file with a unique name and keep its path
1tmpfile=$(mktemp)
# -d creates a temp directory instead
2tmpdir=$(mktemp -d)
# Delete both on exit; double quotes insert the paths when the trap is set
3trap "rm -rf $tmpfile $tmpdir" EXIT
# Write to the temp file
4echo "data" > "$tmpfile"
# Print the generated paths (random names that vary per run)
5echo "Temp file: $tmpfile"
6echo "Temp dir: $tmpdir"

Output

Temp file: /tmp/tmp.Xa1B2c3D
Temp dir: /tmp/tmp.Ef4G5h6I
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 10
  • $× 7
  • -× 2
  • :× 2
  • (× 2
  • )× 2
  • =× 2
  • >× 1

More Shell examples at level 4

← Shell typing practice