Search code examples
batch-fileif-statementconditional-statementsgotofile-exists

Conditional IF EXIST Statement for multiple filenames in BATCH file


I'm working on the following batch script and I'm not sure how I can achieve the results I'm looking for. I searched here as well as online, but I didn't see anything that looked like what I'm looking for. Any help is appreciated.

I need to check if two files exist as well as if they don't. Currently I've got the code below working, however if one file exists or is missing it goes in a 3rd direction (I've updated the code to account for the 3rd direction so now it works fine, but I know there is much room for improvement!). I know it's not pretty, but it works and the pretty code doesn't.

Please note that there are other files in the same directory with the same extensions, so searching by extension will not work.

Working Code:

@echo off
echo checking file structure...
if exist "file1.exe" (
if exist "file2.zip" (
goto ok
)
)

if not exist "file1.exe" (
if not exist "file2.zip" (
goto download
)
)
if not exist "file1.exe" (
goto download
)
)

if not exist "file2.zip" (
goto download
)
)
:download
echo downloading missing files.
:ok
echo Install successful

What I would like to do:

(The following code isn't expected to work, it's my thoughts written out)

@echo off
set file1=setup.exe
set file2=package.zip

if exist $file1 && $file2 then goto ok
else if not exist $file1 || $file2 goto download

Example of why checking for the two files alone will not work

echo checking file structure...
if exist "setup.exe" if exist "package.zip" goto TEST1
if not exist "setup.exe" if not exist "package.zip" goto TEST2
ECHO [Error!] - 1 File is present, the other is missing!
PAUSE
:TEST1
ECHO [Success!] - Found both files, YAY! 
PAUSE
:TEST2
ECHO [Error!] - No matching files found.
PAUSE

Solution

  • The parentheses are neccessary for the else clause.

    @echo off
    echo checking file structure...
    if exist "file1.exe" (
        if exist "file2.zip" (
            goto :ok
        ) else goto :download
    ) else goto :download
    
    :download
    echo downloading missing files.
    :ok
    echo Install successful
    

    But the else isn't required at all because the program flow falls through to the download label

    @echo off
    echo checking file structure...
    if exist "file1.exe" if exist "file2.zip"  goto :ok
    :download
    echo downloading missing files.
    :ok
    echo Install successful