RSSAmplifier

Bash Prompt · Dec 3, 2025

Quickly Create Temporary Files and Directories with mktemp

0
Sign in to vote or save

Elliot Cooper · Bash Prompt

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:

  • -d - Create a temporary directory
  • -p <DIR>- Create the temporary file in the specified directory

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.

Read the original on bash-prompt.net

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.