When you are writing complex bash scripts, you often need a place to temporarily store data—like the intermediate output of a database query or a list of files that need to be processed. While you could just create a file called temp.txt in your current directory, this is dangerous. If you run two instances of the script at the same time, they will both try to write to temp.txt, corrupting the data. Furthermore, you might forget to delete the file when the script finishes. The mktemp (make temporary) command solves this by safely creating mathematically unique, secure temporary files and directories, usually within the system’s /tmp folder.
Creating a Temporary File
To create a safe, temporary file, you simply run the command with no arguments.
mktemp
When you press Enter, the system will create an empty file in the /tmp directory and print the absolute path of that file to the terminal screen (for example: /tmp/tmp.8xYz7AbC). The random string of alphanumeric characters ensures that this file name is globally unique and will never conflict with another process.
Using mktemp in a Bash Script
The true power of mktemp is utilizing it within a script. Because the command prints the path of the newly created file, you can capture that path into a variable and then use that variable throughout your script.
#!/bin/bash
# Create the temporary file and store its path in the MY_TEMP variable
MY_TEMP=$(mktemp)
# Write data into the temporary file
echo "This is some temporary data" > "$MY_TEMP"
# Read the data back
cat "$MY_TEMP"
# Safely delete the temporary file when you are finished
rm "$MY_TEMP"
Creating Temporary Directories
Sometimes you need more than a single file; you need an entire folder to temporarily unpack an archive or compile software. You can instruct mktemp to create a directory instead of a file by using the -d (directory) flag.
mktemp -d
This will generate an empty directory like /tmp/tmp.K9mP2qR and print the path to the screen, ready to be assigned to a variable in your script.
Customizing the File Template
If you want your temporary files to have a recognizable prefix (so you know which script created them while looking at the /tmp directory), you can provide a custom template. The template must end with at least three, but preferably six, capital X characters. The system will replace the X’s with random characters.
mktemp /tmp/my-script-data-XXXXXX
This will generate a file name like /tmp/my-script-data-A1b2C3.