if-statementbatch-filegoto

BAT script to check for multiple files individually else goto 1, 2, etc


I need to be able to check the Public Desktop for file1*, then, if found, exit normally. If file1* is not found, I need it to check for file2*, then, if found, exit normally. If neither file is found, I need it to exit differently, so the script "fails" with a different exit code that another program can use to determine how to proceed.

The wildcards are necessary, as there can be several different numbers after the main name of the files, for instance file1 2024.2 or file1 2021.3, and I don't want to program a line for each, if I don't have to.

The script I'm currently using for testing is sort of functioning, but it will goto :1 whether the file exists on the Public Desktop or not. In fact, I can put any file name in that first if exist and it will goto whichever line is first in the order. (I'll be removing the pauses when the script is working, I just needed them to see where it's exiting.)

if exist "c:\users\public\desktop\file1*" goto :1 ELSE exist "c:\users\public\desktop\file2*" goto :2 ELSE goto :3

:1
echo "File1"
pause
exit /b 0

:2
echo "File2"
pause
exit /b 0

:3
echo "File Not Found"
pause
exit /b 2

I've also tried formatting similar to some other posts that were using if exist statements, which is usually something like:

if exist %filename1% (
    echo "filename1 found"
) ELSE (
    if exist %filename2% (
        echo "filename2 found"
    )

But any time I try any other formatting, the script stops running where I can see it. It quickly flashes in the background and closes, so I can never see what it's doing. (Just using the echo's as an example to see which filename it's picking up, if I could see it run.)


Solution

  • Your code is missing an if after the first ELSE.
    Added ( ) for better readability.

    if exist "c:\users\public\desktop\file1*" (
      goto :1
    ) else if exist "c:\users\public\desktop\file2*" (
      goto :2
    ) else (
      goto :3
    )
    
    :1
    echo "File1"
    pause
    exit /b 0
    
    :2
    echo "File2"
    pause
    exit /b 0
    
    :3
    echo "File Not Found"
    pause
    exit /b 2