Unique Temporary Filename

If you are a Linux/Unix Systems Administrator you have had to create a shell script to do some mundane and repetitive task at one point in your career, for one reason or another. In my personal experience, I have had to create several such shell scripts to accomplish a wide variety of tasks. One thing that I have found to be common among all my shell scripts is the need for unique, yet temporary filename that can be disposed of without a care in the world. Creating a unique filename is very important since you run the risk of erasing and/or appending output to an existing file on your system. Obviously this can have adverse affects and its not what you want to do.

If you are you a shell scripter and you need to create a random, yet unique temporary filename for one of your scripts, here is technique on how I create a random temporary file on my system. Keep in mind that your results will vary since many of the techniques discussed here make use of system wide variables set at startup by your machine. I assume that you have basic knowledge of Linux, shell scripts, and how to execute one.
On to the code:


TEMP_FILE=$HOME/.$(basename $0).$$.$RANDOM

A working shell script using the example code above:

A sample output would yield something similar, but not exactly, too:


]# ./unique_file
/home/user/.unique_file.16090.16402

]# ./unique_file
/home/user/.unique_file.16172.24316

]# ./unique_file
/home/user/.unique_file.16287.26720

etc...

Now lets examine the way we used to create the file. Again, YMWV on your system 😉

  • Name the Bash shell variable:

    TEMP_FILE=
    

  • Set the path to the location of the TEMP_FILE using our $HOME environment variable:

    $HOME/
    

    This will result in /home/user/

  • Create a hidden file using the output of the name of the script

    .$(basename $0)
    

    This will result in .unique_file

  • Use the shell’s current process ID using the $$ parameter

    .$$
    

    In my case, this will result in .16287

  • Add a completely random number in case your program needs more than one temporary file

    .$RANDOM
    

  • Again, in my case, this will result in .26720

You can also use date’s + option to add even more randomness/uniqueness to the filename:

TEMP_FILE=$HOME/.$(basename $0).$$.$RANDOM.$(date +%Y%m%d%H%M%S)

Sample output using the above code:

]# ./unique_file
/home/user/.unique_file.16357.2586.20001218010832

Look at the man page for date. I’m too lazy to explain that one 😉

To some extent this might be overkill but I can guarantee a completely unique and random file name 99.99999~% of the time if you use my method above. Happy shell scripting!


About this entry