Create unique file name Windows batch

2019-01-25 09:37发布

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?

8条回答
太酷不给撩
2楼-- · 2019-01-25 10:04

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.

查看更多
混吃等死
3楼-- · 2019-01-25 10:05
@echo off
:: generate a tempfilename in %1 (default TEMPFILE)
:loop
set /a y$$=%random%+100000
set y$$=temp%y$$:~1,2%.%y$$:~-3%
if exist "%temp%\%y$$%" goto loop
SET "y$$=%temp%\%y$$%"&copy nul "%temp%\%y$$%" >nul 2>NUL
:: y$$ now has full tempfile name
if "%1"=="" (set "tempfile=%y$$%") else (set "%1=%y$$%")

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.

查看更多
登录 后发表回答