Posted in Linux commands

Make temporary Files or directories

Sometimes I need a temporary file or a temporary directory with a unique name in my scripts. Of course I can create a file in /tmp with the actual time in its name. But what if some other user has the same idea, and the scripts run at the same time? Here comes mktemp.

In the minimal form mktemp creates a file in the directory /tmp and gives the filename (with the complete path) on stdout:

$ mktemp
/tmp/tmp.E6ZDn53vyx
$ ls -l /tmp/tmp.E6ZDn53vyx
-rw------- 1 maker users 0 Aug 16 14:15 /tmp/tmp.E6ZDn53vyx

With the parameter -d a directory is created:

$ mktemp -d
/tmp/tmp.VAOcYdM73O
$ ls -ld /tmp/tmp.VAOcYdM73O
drwx------ 2 maker users 6 Aug 16 14:13 /tmp/tmp.VAOcYdM73O

Additionally I can put a hint, which program created the temporary file, into the file or directory name by using a template:

$ mktemp -t myprogXXXXXX
/tmp/myprogP7HUAp

The Xs are replaced by a uniq string, and the rest is used as is.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s