How to check for the existence of a folder in a given relative path?

Solution 1:

Batch file programming is messy.  I can’t find any one solution that works perfectly.  But this three-pronged approach seems to work:

SET CURR_PATH=%CD%

:: Assume/anticipate failure
set "FOLDER_EXIST=False"

cd /d "%INPUT_PATH%\%REL_PATH%" 2> nul  &&  (
    if exist  %FOLDER_NAME%\    set "FOLDER_EXIST=True"
    if exist "%FOLDER_NAME%\"   set "FOLDER_EXIST=True"
    cd %FOLDER_NAME% 2> nul &&  set "FOLDER_EXIST=True"
)
cd /d %CURR_PATH%
echo FOLDER_EXIST = %FOLDER_EXIST%.

Note that the if statements are testing the (candidate) folder name followed by a \.  For example,

    if exist C:\Windows\debug
    if exist C:\Windows\debug\

and

    if exist C:\Windows\notepad.exe

should all succeed, but

    if exist C:\Windows\notepad.exe\

should fail, because C:\Windows\notepad.exe is not a folder.


    if exist  %FOLDER_NAME%\    set "FOLDER_EXIST=True"

will fail if %FOLDER_NAME% contains space(s) and is not quoted; e.g., set "FOLDER_NAME=Program Files".

    if exist "%FOLDER_NAME%\"   set "FOLDER_EXIST=True"

will fail if %FOLDER_NAME% contains space(s) and is quoted; e.g., set FOLDER_NAME="Program Files".  And

    cd %FOLDER_NAME% 2> nul &&  set "FOLDER_EXIST=True"

will fail if you don’t have permission to cd into %FOLDER_NAME%.

Solution 2:

One line version using operator && or || if exist/not exist:

>nul 2>&1 pushd "%cd%\my_Folder" &&(popd & set "Bool=True")|| set "Bool=False"

set Bool & echo=%Bool%