Skip to content

Latest commit

 

History

History
executable file
·
293 lines (201 loc) · 7.12 KB

File metadata and controls

executable file
·
293 lines (201 loc) · 7.12 KB

Conditional Statements in Windows Batch Scripts (IF, IF EXIST)

Windows batch provides several forms of the IF statement:

  1. IF <condition> <command>

  2. IF EXIST <filename> <command>

  3. IF DEFINED <variable> <command>

  4. IF ERRORLEVEL <number> <command>

  5. IF <string1>==<string2> <command>

    ✅ Basic IF Syntax

    IF <condition> (commands) ELSE (commands)

    Or, without parentheses:

    IF <condition> command1 ELSE command2

    However, parentheses are preferred for multi-line blocks and to avoid ambiguity.


1. IF with String Comparisons

  • 🧷 Syntax

    IF "string1"=="string2" (echo match) ELSE (echo no match)

    Always quote your strings to avoid parsing issues, especially when dealing with spaces or empty variables.

  • 🛑 Common Pitfall: Missing Quotes

    :: Problematic when variable is empty!
    IF %USERNAME%==admin echo Welcome
    
    :: Better:
    IF "%USERNAME%"=="admin" echo Welcome

    If %USERNAME% is empty, the first line becomes:

    IF ==admin echo Welcome

    ...which causes a syntax error.


    🔎 Case-Insensitive Matching

    Batch string comparison using == is case-insensitive by default.

    IF "admin"=="ADMIN" echo This will match

    To do case-sensitive comparisons, use CALL with string manipulation or external tools (not natively supported).


    🧠 Variables and Delayed Expansion

    Consider this:

    SET VAR=hello
    IF "%VAR%"=="hello" ECHO match

    Now try:

    SET VAR=hello & SET VAR=world
    IF "%VAR%"=="world" ECHO match

    This won’t work reliably in complex loops. You’ll need delayed variable expansion:

    SETLOCAL ENABLEDELAYEDEXPANSION
    SET VAR=hello
    IF "!VAR!"=="hello" ECHO match
    ENDLOCAL

    Use !VAR! instead of %VAR% when using delayed expansion, especially inside loops or IF blocks.


2. IF EXIST: File/Folder Existence Check

  • ✅ Syntax

    IF EXIST "filename.txt" (
        ECHO File found!
    ) ELSE (
        ECHO File not found!
    )
  • 📁 Checking Directories

    IF EXIST "C:\MyFolder\" ECHO Folder exists

    Yes, folders are treated like files with trailing slashes.

    ❗ Gotcha: Quoted Paths and Wildcards

    Avoid combining wildcards and quotes:

    :: WRONG – This won't work
    IF EXIST "*.txt" echo Match found
    
    :: Correct
    IF EXIST *.txt echo Match found

    Quotes are fine for exact names, not wildcard patterns.

    🔁 Nested IFs

    IF EXIST "file.txt" (
        IF "%MODE%"=="debug" (
            ECHO Found file in debug mode
        ) ELSE (
            ECHO Found file in normal mode
        )
    ) ELSE (
        ECHO File not found
    )

    Just like other languages, you can nest conditionals, but be mindful of readability.


🆚 Comparing Numbers vs Strings

  • All IF string comparisons using == are string-based, not numeric.

    SET A=10
    SET B=2
    IF %A% GTR %B% echo A is greater
  • 🔢 Numeric Comparison Operators

    Use these:

    • EQU – Equal
    • NEQ – Not equal
    • LSS – Less than
    • LEQ – Less than or equal
    • GTR – Greater than
    • GEQ – Greater than or equal

    Example:

    SET /A A=5
    IF %A% GEQ 3 echo A is 3 or more

    🔍 %A% GEQ 3 works only if both sides are numeric.


3. IF ERRORLEVEL

  • Checks the exit code from the previous command:

    ping -n 1 127.0.0.1
    IF ERRORLEVEL 1 (
        ECHO Ping failed
    ) ELSE (
        ECHO Ping succeeded
    )

    Important:

    IF ERRORLEVEL 2 …  :: Matches 2, 3, 4, … (NOT just 2)
  • To check for exact error level, check from highest to lowest:

    IF ERRORLEVEL 3 (
        ECHO 3 or more
    ) ELSE IF ERRORLEVEL 2 (
        ECHO 2
    ) ELSE IF ERRORLEVEL 1 (
        ECHO 1
    )

4. IF DEFINED

  • Checks if a variable exists:

    IF DEFINED PATH (
        ECHO PATH is set
    ) ELSE (
        ECHO PATH is not set
    )
Great for checking if user or system variables are available.

🛑 Common Mistakes

Mistake Why it’s a problem
Unquoted strings Breaks when variables are empty or contain spaces
No delayed expansion in loops %VAR% gets stale values
Wrong file path in IF EXIST Missing quotes, wrong slashes, case sensitivity
Assuming ERRORLEVEL means exact It's ≥ comparison, not equality

🧪 Real-world Example: Backup Script

@ECHO OFF
SET FILE=backup.zip

IF EXIST "%FILE%" (
    ECHO Found existing backup. Deleting...
    DEL "%FILE%"
)

ECHO Creating new backup...
REM simulate backup with dummy file
COPY NUL "%FILE%"

IF EXIST "%FILE%" (
    ECHO Backup created successfully.
) ELSE (
    ECHO Backup failed!
)

🧠 Pro Tip: Combine Conditions

IF EXIST "input.txt" IF "%MODE%"=="prod" (
    ECHO Processing file in prod mode
)

Or use nested form for clarity.


📘 Summary

Type Example Description
String Compare IF "%A%"=="B" String equality
File Check IF EXIST "file.txt" File or folder presence
Variable Check IF DEFINED MYVAR Whether a variable is defined
Numeric Compare IF %X% GTR 3 Numerical comparisons
Exit Code IF ERRORLEVEL 1 Previous command's exit status