How to: create a temporary file securely
Q. How do I create a temporary file securely under UNIX Bash shell?
A. There are many ways:
[a] mktemp command - make temporary unique filename
[b] $RANDOM - Use $RANDOM variable
mktemp command
From the man page:
The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX.
For example, create a temporary file:
$ mktemp /tmp/output.XXXXXXXXXX
Output:
/tmp/output.qBYDtF7199
Send ls command output to /tmp/output.qBYDtF7199:
$ ls > /tmp/output.qBYDtF7199
However, you may need to store temporary file name /tmp/output.qBYDtF7199 to a shell variable:
TMPFILE=$(mktemp /tmp/output.XXXXXXXXXX)
ls > $TMPFILE
Create a temporary directory
The -d option makes a directory instead of a file.
TMPDIR=$(mktemp -d /tmp/output.XXXXXXXXXX)
cd $TMPDIR
# do something
Another example:
TMPFILE=‘mktemp -t /tmp/out.myapp.XXXXXXXXXX‘ && {
# Safe to use $TMPFILE in this block
echo data > $TMPFILE
...
# do something
# clean up
rm -f $TMPFILE
}
Using $RANDOM variable
Bash also provide $RANDOM variable with random value, you can use the same to create a file or directory:
TEMFILE=/tmp/$RANDOM > $TEMFILE # create directory TEMDIR=/tmp/$RANDOM.$RANDOM mkdir $TEMDIR # do something...
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Other Helpful FAQs:
- /usr/libexec/mysqld: Can’t create/write to file ‘/tmp/’ (Errcode: 13)
- How do I permanently erase hard disk?
- Restore a backup of a MySQL Database Server
- Linux or UNIX securely copy files across a network computer
- How to Tunnel X Windows Securely over SSH
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: $RANDOM, /tmp/output.XXXXXXXXXX file, BASH Shell, mktemp_command, random variable, shell variable, temporary file, tmp, UNIX



November 30th, 2007 at 1:27 pm
do not ever use $RANDOM for creating files or directories…! mktemp can create also a directory if you use -d option. the “mkdir somethin” (where something can be $RANDOM or whatever else) suffers from race conditions. what would you do if directory was already there and not owned by you? with mktemp -d you have no problems.
November 30th, 2007 at 2:41 pm
matej,
Actually, I talked about -d option, but forgot to type -d.
I appreciate your post.