Quickly Create Temporary Files and Directories with mktemp

When scripting, it is often necessary to store some temporary data. This is not persistent data, it does not hold any important information that needs to be retained for longer than the execution of the script.

I’ve used lots of methods to create temporary directories and files that I end up recreating every time.

That is, until I found mktemp.

How To Use mktemp

By default, mktemp will create files and directories under /tmp/. This means they will be deleted on reboot on almost all modern Linux distributions.

The only two options that I use are the following:

For example, first create a directory:

mktemp -d
/tmp/tmp.XiirR9jKM6

Then create a temporary file in that directory:

mktemp -p /tmp/tmp.XiirR9jKM6
/tmp/tmp.XiirR9jKM6/tmp.SI47kjpzYL

Using mktemp In A Script

Putting this into a script will look something like the following:

!#/bin/bash

tempDir=$(mktemp -d)
tempFile=$(mktemp -p $tempDir)

You can now write to $tempFile or make more files in $tempDir.