I have seen many posts about creating a unique filename from the naive %TIME% to the plausible (but insufficient) %RANDOM%. Using wmic os get localdatetime
is much better, but it can still fail on multiple CPU/core machines. The following script will eventually fail when run in 5+ shells on a multple core machine.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%i IN (0, 1, 1000) DO (
FOR /F "usebackq" %%x IN (`wmic os get localdatetime ^| find "."`) do (set MYDATE=%%x)
ECHO MYDATE is now !MYDATE!
IF EXIST testuniq_!MYDATE!.txt (
ECHO FAILED ON !MYDATE!
GOTO TheEnd
)
COPY NUL >testuniq_!MYDATE!.txt
)
:TheEnd
EXIT /B 0
Does anyone have a reliable way to create a unique file name in a shell script?
make the file contents an object, use the pointer memaddress as the first part of your file name and a Rand() as your second part. the memory address will be unique for all objects even with multiple instances running.
Here's a cut-down version of my tempfile generator to create a file named
tempnn.nnn
in the%temp%
directory.Once
tempnn.nnn
has been created, then it's simple to create as many further tempfiles as you like for the process by appending a suffix to%y$$%
, eg%y$$%.a
etc. Of course, that presumes that some other process doesn't randomly create filenames without using this procedure.