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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With