How to create unique file names in bash shell


2 min read

For debugging purposes, we had to profile a Python program using cProfile which will create a .prof file with the profiled data. Also, we wanted to create unique file names for each run using a bash shell.

We had a couple of options:

  • Use Unix epoch time which is a number and can be suffixed to a file to make it unique.

  • Use uuidgen to create a GUID. Since it is for dev/debugging purposes, we wanted to shorten it and use only the last part of the GUID. I am quite aware that just using the last part may not be always unique, it is for some dev/debugging so it is okay for our purposes.

We will run through to how to generate a unique file name using both the methods below:

In the below script, we are using $(date +"%s") which provide the current date time as an epoch. The output is something like

PROFILE_FILE=test-$(date +"%s").prof

with the below script, we using a combination of uuidgen and piping it to cut to get the last part of GUID. The output is like With regards to the args for cut, -d "-" argument refers to using - as the delimiter and -f5 argument refers to getting the 5th field from the array after splitting it

PROFILE_FILE=test-$(uuidgen | cut -d "-" -f5).prof