Batch if
if runs a command only when a condition is true. CMD's if is less general than in other languages: there is a fixed set of condition forms, no and/or, and no elseif keyword. With a few patterns you can still express anything you need.
| Form | True when |
|---|---|
if "a"=="b" cmd |
the two strings are identical (case-sensitive) |
if /i "a"=="b" cmd |
the strings are equal ignoring case |
if a equ b cmd |
comparison operators, numeric when both sides are numbers |
if exist path cmd |
the file or folder exists |
if defined var cmd |
the variable exists |
if errorlevel n cmd |
the last exit code is n or higher |
if not ... cmd |
negates any of the above |
Comparing strings
== compares text exactly. Always put quotes on both sides: if a variable is empty or contains spaces, the unquoted form turns into invalid syntax.
@echo off
set "lang=Rust"
if "%lang%"=="Rust" echo exact match
if "%lang%"=="rust" echo this does not print
if /i "%lang%"=="rust" echo match ignoring case
if not "%lang%"=="Go" echo not Goexact match
match ignoring case
not Go
Here's why the quotes matter. With set "lang=" (undefined), if %lang%==Rust becomes if ==Rust, which CMD rejects with The syntax of the command is incorrect. and stops the script. With quotes it becomes if ""=="Rust", a valid comparison that is simply false.
else and blocks
To run several commands, or to add else, use parentheses. The rules are strict: else must be on the same line as the closing ) of the if-block, and the opening ( must be on the same line as the if.
@echo off
set /a score=72
if %score% geq 50 (
echo Passed
echo Score: %score%
) else (
echo Failed
)Passed
Score: 72
On one line: if exist out.txt (echo yes) else (echo no).
else if
There's no elseif, but the else branch can contain another if, which gives you the same chain:
@echo off
for %%s in (95 72 40) do (
if %%s geq 90 (
echo %%s: grade A
) else if %%s geq 60 (
echo %%s: grade B
) else (
echo %%s: grade C
)
)95: grade A
72: grade B
40: grade C
Comparison operators
For numbers, use the three-letter operators. When both sides are valid numbers they compare numerically; otherwise they compare as text.
| Operator | Meaning |
|---|---|
equ |
equal |
neq |
not equal |
lss |
less than |
leq |
less than or equal |
gtr |
greater than |
geq |
greater than or equal |
@echo off
if 10 gtr 9 (echo numeric: 10 is greater than 9)
if "10" gtr "9" (echo text: "10" is greater) else (echo text: "10" sorts before "9")
if 007 equ 7 echo 007 equals 7numeric: 10 is greater than 9
text: "10" sorts before "9"
007 equals 7
Quoting a number makes it text, and text compares character by character: "1" comes before "9". So for numeric comparisons, leave the operands unquoted, and make sure the variable actually holds a number (an empty variable would cause a syntax error; if "%n%"=="" ... first, or use if defined n). Don't use < or >: in CMD those are redirection characters, and if 3 > 2 echo yes writes yes into a file called 2.
Testing files and folders
if exist takes a path, and wildcards work. To test specifically for a folder, append a backslash, if exist "logs\":
@echo off
mkdir logs
> notes.txt echo hello
if exist notes.txt echo notes.txt exists
if exist *.txt echo there is at least one .txt file
if exist "logs\" echo logs is a folder
if not exist "notes.txt\" echo notes.txt is not a folder
if not exist missing.txt echo missing.txt does not existnotes.txt exists
there is at least one .txt file
logs is a folder
notes.txt is not a folder
missing.txt does not exist
A common guard creates a folder only when it isn't there yet: if not exist "out\" mkdir out.
Testing variables
@echo off
set "mode=fast"
if defined mode echo mode is set to %mode%
if not defined level (
echo level is not set, using 1
set "level=1"
)
echo level=%level%mode is set to fast
level is not set, using 1
level=1
Combining conditions
There's no and or or, so you combine conditions by hand.
AND: nest the ifs. The second if is the command of the first:
@echo off
set /a age=30
set "member=yes"
if %age% geq 18 if /i "%member%"=="yes" echo adult member: discount appliesadult member: discount applies
OR: use a flag variable:
@echo off
set "day=Sun"
set "weekend="
if /i "%day%"=="Sat" set "weekend=1"
if /i "%day%"=="Sun" set "weekend=1"
if defined weekend (echo %day% is a weekend day) else (echo %day% is a weekday)Sun is a weekend day
To check a value against a list, a for loop is often shorter: for %%d in (Sat Sun) do if /i "%day%"=="%%d" set "weekend=1".
&& and ||: if based on success
For the common question "did the last command work?", you don't need if at all. a && b runs b only if a succeeded (exit code 0); a || b runs b only if a failed:
@echo off
> fruits.txt echo apple
>> fruits.txt echo banana
findstr /i "banana" fruits.txt >nul && echo banana found || echo no banana
findstr /i "cherry" fruits.txt >nul && echo cherry found || echo no cherrybanana found
no cherry
The if errorlevel form and %errorlevel% are covered in Exit Codes & errorlevel.
A trap: variables inside blocks
The whole parenthesised block is read and its %variables% are expanded before any line of it runs. A variable set inside the block therefore still shows its old value inside that same block:
@echo off
set "state=old"
if 1==1 (
set "state=new"
echo inside the block: %state%
)
echo after the block: %state%inside the block: old
after the block: new
The fix is delayed expansion (!state!), the subject of setlocal & Delayed Expansion.
Comparison with other shells
| Task | CMD | Bash | PowerShell |
|---|---|---|---|
| strings equal | if "%a%"=="%b%" |
[[ $a == "$b" ]] |
if ($a -ceq $b) |
| ignore case | if /i |
shopt -s nocasematch |
-eq (default) |
| numbers | if %n% gtr 5 |
(( n > 5 )) |
$n -gt 5 |
| file exists | if exist f |
[[ -e f ]] |
Test-Path f |
Learn more: Bash if/else, PowerShell if/else, goto & Labels.
Test yourself
Where must else be written?
- On its own line after the block
- On the same line as the closing ) of the if-block
- Anywhere inside the block
- Before the if
Which line tests 'count is greater than 10' numerically?
- if %count% > 10 echo big
- if "%count%" gtr "10" echo big
- if %count% gtr 10 echo big
- if %count% -gt 10 echo big
How do you check whether build is a folder?
- if exist build
- if exist "build\"
- if folder build
- if defined build