0

The first half of the question is answered here.

The solution to create a folder only if it doesn't exist in a batch file is the following: if not exist "C:\FOLDER_NAME" mkdir C:\FOLDER_NAME

The problem we're facing is this batch file is being run in parallel. For business reasons we can't change the timing of when these batch file are started. Two of the jobs are clearly passing the if statement, but one is creating the folder and the other raises the error "A subdirectory or file FOLDER_NAME already exists".

The %ERRORLEVEL% = 1, and the thought was to simply do the following: if %ERRORLEVEL% gtr 1 goto errorexit. Access is denied is also %ERRORLEVEL% = 1 so this solution isn't feasible; this error stills need to exit the batch process.

How does one deal with race conditions when using mkdir in this context?

Chris
  • 11
  • 4
  • I use in batch file always first `md "C:\FOLDER_NAME" 2>nul` to create the folder independent on already existing or not and suppress the error message on folder existing or could not be created at all like on missing appropriate NTFS permissions or there is already a file with that name and use next `if not exist "C:\FOLDER_NAME\" echo ERROR: Failed to create folder "C:\FOLDER_NAME"& exit /B 1`. The backslash at end of folder name is important as otherwise is just checked if there is any file system entry with name `C:\FOLDER_NAME` which can be also a file or a symbolic link to a file. – Mofi Feb 23 '23 at 17:01

1 Answers1

0
FOR /f "delims=" %%e IN ('MD "%targetdir%" 2^>^&1') DO (
 ECHO %%e|FIND "or file">NUL
 IF ERRORLEVEL 1 (ECHO Access denied) ELSE (ECHO already exists/other)
)

Where targetdir contains the required directory name.

If an error occurs, %%e contains either "A subdirectory or file FOLDER_NAME already exists" or some other message.

Magoo
  • 77,302
  • 8
  • 62
  • 84