Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch files: If directory exists, do something

I'm trying to do the following:

IF EXISTS ("C:\Users\user\Desktop\folder1\") {

MOVE "C:\Users\user\Desktop\folder2\" "C:\Users\user\Desktop\folder1\"
RENAME "C:\Users\user\Desktop\folder1\folder2\" "folder3"

} else {

MKDIR "C:\Users\user\Desktop\folder1\"
MOVE "C:\Users\user\Desktop\folder2\" "C:\Users\user\Desktop\folder1\"
RENAME "C:\Users\user\Desktop\folder1\folder2\" "folder3"
}

With the following code:

  @ECHO ON

IF EXIST "C:\Users\user\Desktop\folder1\" (GOTO MOVER)

PRINT "It doesn't exists - This is just for debugging"
PAUSE

:MOVER
ECHO "MOVER"
PAUSE
EXIT
:END

But the system does not print the test words.

like image 686
Julian Moreno Avatar asked Apr 28 '15 21:04

Julian Moreno


2 Answers

IF EXIST checks only if a file exists and cannot check folders. Usually, you test like this

IF NOT EXIST "myfolder\NUL" mkdir "myfolder"

The pseudo device NUL acts like a file and does in fact exist in every folder. Note the spelling.

But I have seen that test fail in batchfiles, for unknown reasons. So I suggest this instead:

CD myfolder 2>NUL && CD .. || MD myfolder

CD myfolder tries a legal operation with the folder and the conditional execution of MD/MKDIR creates the folder only if that operation fails. CD .. reverts the action if the folder should exist. 2>NUL suppresses the error message if the folder does not exist.

edit: Apparantly there is a simpler method for testing: append a backslash (\) to the foldername to make it syntactically a folder, like this:

if not exist myfolder\ md myfolder || goto :EOF

This will create the folder "myfolder" if it does not yet exist. Additionally, in case there is a file named "myfolder" the MD will fail and the batch file will be terminated after the error message is displayed. Also, ERRORLEVEL will be set. I like this more as the error output doesn't have to be redirected.

edit: If you want to execute several commands, run them in a subshell, that is, enclose them in parantheses like this:

if not exist myfolder\ (  
    md myfolder
    dir myfolder
    REM ...or run any other commands
) || goto :EOF  
like image 108
user1016274 Avatar answered Oct 04 '22 03:10

user1016274


IF EXIST can check for folders I use it this way:

IF EXIST %local_path%\opensource\eclipse rmdir %local_path%\opensource\eclipse /s /q >nul
like image 40
schwdk Avatar answered Oct 04 '22 03:10

schwdk