Temporary file naming and random numbers
Shell scripts often need to store temporary data. The most suitable location to do this is /tmp
(which will be cleaned out by the system on reboot). There are two methods to generate standard filenames for temporary data.
How to do it...
The mktemp
command will create a unique temporary file or folder name:
- Create a temporary file:
$ filename=`mktemp` $ echo $filename /tmp/tmp.8xvhkjF5fH
This creates a temporary file, stores the name in filename, and then displays the name.
- Create a temporary directory:
$ dirname=`mktemp -d` $ echo $dirname tmp.NI8xzW7VRX
This creates a temporary directory, stores the name in filename, and displays the name.
- To generate a filename without creating a file or directory, use this:
$ tmpfile=`mktemp -u` $ echo $tmpfile /tmp/tmp.RsGmilRpcT
Here, the filename is stored in $tmpfile
, but the file won't be created.
- To create the temporary filename based on a template, use...