Babu Annamalai
Babu Annamalai's Blog

Follow

Babu Annamalai's Blog

Follow
How to create unique file names in bash shell

Photo by Jeff Sheldon on Unsplash

How to create unique file names in bash shell

Babu Annamalai's photo
Babu Annamalai
ยทApr 12, 2023ยท

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 test-1681287886.prof

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

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 test-5F4C3E649454.prof. 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
echo ${PROFILE_FILE}
ย 
Share this