DEV Community

Babu Annamalai
Babu Annamalai

Posted on • Originally published at mysticmind.dev

How to create unique file names in bash shell

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 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}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)