if can be used to conditionally execute parts in a batch file.
Simplest form
In its simplest form, the if keyword is followed by a comparison (or condition) and a command. The command is executed if the comparision is true.
In the following example, the if statement is prefixed with an at sign (@) in order to prevent the batch file interpreter from echoing the entire if statement when executed.
Using parentheses also allow to add more than one command to be executed to the true or false part of an if statement. I generally find they make it easier to read if statements:
@echo off
if "%1" equ "foo" (
echo This is the foo
echo ---------------
echo Paranthteses allow to add
echo more than one comamd
) else (
echo This is NOT the foo
echo -------------------
)
Multiple if … else if … else statements can be chained:
@echo off
if %1 == foo (
echo the first argument
echo is foo
) else if %1 == bar (
echo the first argument
echo is bar
) else if %1 == baz (
echo the first argument
echo is baz
) else (
echo The first argument
echo is neither foo nor
echo bar nor baz.
)
Verifiying that an argument was passed to a batch file
The previous examples assumed that the batch files were invoked with at least one argument. It generally is good practice to verify such an assumption in a batch file:
@echo off
if [%1] neq [] goto ok
echo you need to pass an argument
exit /b
:ok
@echo You have specified %1
if followed by the keyword exist (not exists) checks if a file exists. if exist can also be used on wildcards (such as *.txt):
@echo off
if exist exist.bat (
echo The file exists
) else (
echo The file does not exists
)
if exist foo.bar (
echo The file exists
) else (
echo The file does not exists
)
if exist *.bat (
echo There are .bat files in this directory
) else (
echo No .bat files in this directory
)
if exist *.txt (
echo There are .txt files in this directory
) else (
echo No .txt files in this directory
)
It is also possible to check if a file does not exist with if not exist….
Comparison operators
There are seven comparison operators:
equ
equal
neq
not equal
lss
less than
leq
less than or equal
gtr
greater than
geq
greater than or equal
==
equal (always compares alphabetically?)
If both compared values are integers (positive or negative), they're compared numerically, otherwise, they're comparred alphabetically. This is demonstrated with the following batch file: