- Overview
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Computers are all about 1’s and 0’s, right? So, we need a way to handle when some condition is 1, or else do something different
when it’s 0.
The good news is DOS has pretty decent support for if/then/else conditions.
Checking that a File or Folder Exists
IF EXIST "temp.txt" ECHO found
Or the converse:
IF NOT EXIST "temp.txt" ECHO not found
Both the true condition and the false condition:
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
NOTE: It’s a good idea to always quote both operands (sides) of any IF check. This avoids nasty bugs when a variable doesn’t exist, which causes
the the operand to effectively disappear and cause a syntax error.
Checking If A Variable Is Not Set
IF "%var%"=="" (SET var=default value)
Or
IF NOT DEFINED var (SET var=default value)
Checking If a Variable Matches a Text String
SET var=Hello, World!
IF "%var%"=="Hello, World!" (
ECHO found
)
Or with a case insensitive comparison
IF /I "%var%"=="hello, world!" (
ECHO found
)
Artimetic Comparisons
SET /A var=1
IF /I "%var%" EQU "1" ECHO equality with 1
IF /I "%var%" NEQ "0" ECHO inequality with 0
IF /I "%var%" GEQ "1" ECHO greater than or equal to 1
IF /I "%var%" LEQ "1" ECHO less than or equal to 1
Checking a Return Code
IF /I "%ERRORLEVEL%" NEQ "0" (
ECHO execution failed
)
<< Part 4 – stdin, stdout, stderr
Part 6 – Loops >>
Like any scripting or programming language, the batch language provides conditional execution, i.e.
if condition then command [ else command ]
In DOS (COMMAND.COM), condition
can be:
[NOT] ERRORLEVEL number [/I] [NOT] string1==string2 [NOT] EXIST filename
In NT (CMD.EXE, Windows NT 4 and later) numerical comparisons were added:
number1 EQU number2
(true if numbers are equal)
number1 NEQ number2
(true if numbers are not equal
number1 GTR number2
(true if number1
is greater than number2
)
number1 GEQ number2
(true if number1
is greater than or equal to number2
)
number1 LSS number2
(true if number1
is less than number2
)
number1 LEQ number2
(true if number1
is less than or equal to number2
)
Comparisons are really basic, i.e. IF %a% GTR %b%
will work, IF %a% + %b% GTR %c%
will not.
In the batch language, the keyword then
is not used:
IF condition command
The else
keyword was introduced in CMD.EXE, and requires «grouping» with parentheses:
IF condition ( command ) ELSE ( command )
or:
IF condition (command) ELSE (command)
or:
IF condition (command) ELSE command
Note: | Whenever it says (command) with parentheses, you may insert multiple commands, as will be explained later on this page. |
The latter is quite interesting, as it allows ELSE IF
constructions:
IF condition1 ( command1 ) ELSE IF condition2 ( command2 ) ELSE IF condition3 ( command3 ) ELSE IF condition4 ( command4 ) ELSE ( command_none )
Much better than:
IF condition1 ( command1 ) ELSE ( IF condition2 ( command2 ) ELSE ( IF condition3 ( command3 ) ELSE ( IF condition4 ( command4 ) ELSE ( command_none ) ) ) )
Complex conditions
Both COMMAND.COM and CMD.EXE batch language lack and
and or
statements to combine conditions into a «complex condition».
The and
statement is fairly easy to emulate in COMMAND.COM and CMD.EXE alike:
IF condition1 IF condition2 ECHO Condition1 AND Condition2 were both met
or (CMD.EXE only):
IF condition1 ( IF condition2 ( ECHO Condition1 AND Condition2 were both met ) )
The or
functionality requires more code:
SET AtLeastOneConditionMet=false IF condition1 SET AtLeastOneConditionMet=true IF condition2 SET AtLeastOneConditionMet=true IF "%AtLeastOneConditionMet%"=="true" ECHO Condition1 OR condition2 OR both were met
One-Liners
Most program executables set an ErrorLevel stating success or failure of their execution.
This allows for error handling by using IF ERRORLEVEL 1 ...
or IF %ErrorLevel% NEQ 0 ...
, e.g.:
DIR somefolder IF %ErrorLevel% EQU 0 ( ECHO Directory "somefolder" exists ) ELSE ( ECHO Directory "somefolder" does not exist )
CMD.EXE for both OS/2 and Windows NT 4 and later offer a way to create «one-liners», making the error handling code a bit simpler:
One-Liners | ||
---|---|---|
Syntax | Description | Equivalent to |
command1 & command2 |
Execute command2 after execution of command1 has finished | command1 |
command1 && command2 |
Execute command2 only if execution of command1 has finished successfully | command1 |
command1 || command2 |
Execute command2 only if execution of command1 has finished unsuccessfully | command1 |
Note: | Conditional execution based on success or failure of a previous command will only work if that previous command sets an ErrorLevel based on its success or failure. |
Some examples:
FORMAT A: /Q && COPY C:\DATA\*.* A:
will copy all files from C:\DATA to diskette IF and ONLY IF the format succeeds.
XCOPY C:\*.* D:\ /S 2>&1> NUL || ECHO Something terrible happened
will display your own custom error message if XCOPY fails.
Complex One-Liners
What if we want a number of commands to be executed, and abort if any of these commands fails?
command1 IF %ErrorLevel% EQU 0 ( command2 IF %ErrorLevel% EQU 0 ( command3 IF %ErrorLevel% NEQ 0 ( ECHO Error 3 ) ) ELSE ( ECHO Error 2 ) ) ELSE ( ECHO Error 1 )
If we are not interested in the distinction between errors 1,2 or 3, we can simplify the code:
command1 && command2 && command3 || ECHO Error
For simple commands this will work, but sometimes I got unexpected results in constructions like these.
Darin Schnetzler found a more reliable way to write these one-liners:
(command1) && (command2) && (command3) || (ECHO Error)
If any command in the «chain» fails, the rest will be skipped and the error handling (in this case ECHO Error
) will be executed.
The parentheses allow (sub)grouping of commands too:
(command1 & command2) && (command3) && (command4) || (ECHO Error)
In this case, if command1
fails, command2
will still be executed, and if command2
succeeds, command3
will be executed, etc.
Error handling will only be triggered by failure of command2
.. command4
Warning | Batch code can soon become unreadable using these one-liner constructions. You may want to spread the code over multiple lines again: ( |
Thanks Darin
page last modified: 2022-03-23; loaded in 0.0013 seconds
The `if` command in CMD allows you to execute specific commands based on whether a given condition is true or false.
if EXIST "file.txt" (echo File exists) else (echo File does not exist)
What is the If Else Statement?
The If Else construct is a pivotal component of scripting in CMD (Command Prompt). It allows you to execute specific commands based on certain conditions, enabling you to automate tasks and handle decision-making processes in your scripts effectively. Understanding how to use If Else statements is essential for anyone looking to enhance their command line skills and improve their automation capabilities.
Read File in Cmd: A Simple Guide to Easy File Access
Syntax of CMD If Statement
The syntax of the If statement in CMD is quite simple yet powerful. The basic structure is as follows:
if condition command
In this syntax:
- condition is an expression that is evaluated to determine if it is true or false.
- command is the action performed if the condition evaluates to true.
For instance, you might check for the existence of a file using:
if exist "file.txt" echo File exists
In this example, the CMD command checks if “file.txt” exists in the current directory. If it does, it outputs «File exists» to the console.
You can also group multiple commands or conditions by encapsulating them in parentheses, enhancing the clarity and functional grouping of your script.
Rename File in Cmd: A Quick Guide
Understanding the Then Clause
What is the Then Clause?
While CMD doesn’t explicitly use the keyword ‘then’ like other programming languages, the actions that follow an If statement act as the «Then» of conditional checks. Essentially, if the condition is true, the specified command executes immediately after the condition.
Implementing Actions in the Then Clause
You can implement actions in the «then» position by placing them in parentheses. Consider a situation where you need to check if a file exists and echo different outputs based on the outcome:
if exist "file.txt" (echo File exists) else (echo File does not exist)
In this example, if «file.txt» is present, CMD will output «File exists.» If not, it will display «File does not exist.»
Open Files in Cmd: A Simple Guide for Quick Access
The Else Clause in CMD
Purpose of the Else Clause
The else clause is essential for defining what happens when your initial condition evaluates to false. It allows you to provide alternative actions if the criteria set in your If statement are not met.
Example Implementations of Else
One illustrative example of using the else clause involves checking for command line arguments. You might want to provide feedback based on whether an argument was passed when running a script:
if "%1"=="" (echo No argument provided) else (echo Argument provided: %1)
In this snippet, if no argument is provided, the CMD will output «No argument provided.» However, if an argument is received, it will echo back the argument itself.
Create File in Cmd: A Quick Guide to Getting Started
Advanced If Else Conditions
Nested If Else Statements
Sometimes, you may need to evaluate more than one condition. This is where nested If Else statements come into play. By nesting If statements within an else clause, you can create intricate branching logic.
For example, consider the following snippet, which checks for the existence of different files:
if exist "file.txt" (
echo File exists
) else (
if exist "file.bak" (
echo Backup file exists
) else (
echo No files found
)
)
In this case, if «file.txt» exists, it echoes «File exists.» If not, it checks for «file.bak.» If that exists, it outputs «Backup file exists.» If neither file is found, it notifies the user with «No files found.»
Using Comparisons with If Else
String Comparisons
String comparison is straightforward in CMD. You can compare two strings and execute commands based on whether they match:
if "Hello"=="Hello" (echo Strings match) else (echo Strings do not match)
This example will output «Strings match» since both strings are identical.
Numeric Comparisons
Numeric comparisons in CMD involve operators such as GTR (greater than), LSS (less than), and others that allow you to evaluate numeric conditions effectively. Here’s a simple example:
set num=5
if %num% GTR 3 (echo Number is greater than 3) else (echo Number is not greater than 3)
This code sets a variable `num` to 5 and checks if it is greater than 3, outputting the appropriate message.
Mastering IP Scan in Cmd: A Quick Guide
Common Pitfalls with If Else in CMD
When using If Else statements in CMD, there are common pitfalls you should be aware of:
- Missing Syntax Elements: Failing to include necessary elements like quotation marks or parentheses can lead to errors.
- Incorrect Nesting: Improperly nested If statements can cause unexpected behavior in your scripts.
To troubleshoot commands effectively, always ensure parentheses are correctly placed and ensure variable expansions utilize the correct syntax.
Mastering Grep in Cmd: A Quick Guide
Best Practices for Writing CMD If Else Statements
To ensure your CMD scripts are clear and maintainable:
- Aim for readability by using comments to explain complex sections.
- Structure your If Else statements logically, grouping related actions to reduce confusion.
- Properly format your code to make it easily readable by others, facilitating future updates or maintenance.
Mastering Exit in Cmd: A Quick Guide
Conclusion
Mastering the use of if else in CMD can significantly enhance your scripting and automation skills. By understanding the syntax, application, and potential pitfalls, you can create robust scripts that improve productivity. The examples provided illustrate just a few ways to leverage If Else statements effectively. As you continue to practice and implement these constructs, you’ll find even more creative applications in your CMD scripting endeavors.
Ip Reset Cmd: A Quick Guide to Resetting Your IP Address
Additional Resources
For further reading and exploration of CMD commands, consider diving into online communities, forums, and dedicated articles that focus on batch scripting. By connecting with other enthusiasts, you can expand your knowledge and share insights to improve your CMD skills.
Conditionally perform a command.
File syntax IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command)
String syntax IF [/I] [NOT] item1==item2 command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax IF [NOT] DEFINED variable command IF [NOT] ERRORLEVEL number command IF CMDEXTVERSION number command key item A text string or environment variable, for more complex comparisons, a variable can be modified using either Substring or Search syntax. command The command to perform. filename A file to test or a wildcard pattern. NOT perform the command if the condition is false. == perform the command if the two strings are equal. /I Do a case Insensitive string comparison. compare-op can be one of EQU : Equal NEQ : Not equal LSS : Less than < LEQ : Less than or Equal <= GTR : Greater than > GEQ : Greater than or equal >= This 3 digit syntax is necessary because the > and < symbols are recognised as redirection operators
IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
ERRORLEVEL
There are two different methods of checking an errorlevel, the first syntax ( IF ERRORLEVEL … ) provides compatibility with ancient batch files from the days of Windows 95.
The second method is to use the %ERRORLEVEL% variable providing compatibility with Windows 2000 or newer.
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE whether the errorlevel is 0, 1 or 5 or 64
IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64
IF NOT ERRORLEVEL 1 means if ERRORLEVEL is less than 1 (Zero or negative).
This is not very readable or user friendly and does not easily account for negative error numbers.
Using the %ERRORLEVEL% variable is a more logical method of checking Errorlevels:
IF %ERRORLEVEL% NEQ 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
This allows you to trap errors that can be negative numbers, you can also test for specific errors:
IF %ERRORLEVEL% EQU 64 …
To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF.
Test if a variable is empty
To test for the existence of a command line parameter – use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
When comparing against a variable that may be empty, we include a pair of brackets [ ] so that if the variable does happen to be empty the IF command still has something to compare: IF [] EQU [] will return True.
You can in fact use almost any character for this a ‘~’ or curly brackets, { } or even the number 4, but square brackets tend to be chosen because they don’t have any special meaning.
When working with filenames/paths you should always surround them with quotes, if %_myvar% contains “C:\Some Path” then your comparison becomes IF [“C:\Some Path”] EQU []
if %_myvar% could contain empty quotes, “” then your comparison should become IF [%_myvar%] EQU [“”]
if %_myvar% will never contain quotes, then you can use quotes in place of the brackets IF “%_myvar%” EQU “”
However with this pattern if %_myvar% does unexpectedly contain quotes, you will get IF “”C:\Some Path”” EQU “” those doubled quotes, while not officially documented as an escape will still mess up the comparison.
Test if a variable is NULL
In the case of a variable that might be NULL – a null variable will remove the variable definition altogether, so testing for a NULL becomes:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
To test for the existence of a user variable use SET VariableName, or IF DEFINED VariableName
Test the existence of files and folders
IF EXIST filename Will detect the existence of a file or a folder.
The script empty.cmd will show if the folder is empty or not (this is not case sensitive).
Parenthesis
Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands:
IF EXIST filename.txt ( Echo deleting filename.txt Del filename.txt ) ELSE ( Echo The file was not found. )
When combining an ELSE statement with parentheses, always put the opening parenthesis on the same line as ELSE.
) ELSE ( This is because CMD does a rather primitive one-line-at-a-time parsing of the command.
When using parentheses the CMD shell will expand [read] all the variables at the beginning of the code block and use those values even if the variables value has just been changed. Turning on DelayedExpansion will force the shell to read variables at the start of every line.
Pipes
When piping commands, the expression is evaluated from left to right, so
IF SomeCondition Command1 | Command2is equivalent to:
(IF SomeCondition Command1 ) | Command2
The pipe is always created and Command2 is always run, regardless whether SomeCondition is TRUE or FALSE
You can use brackets and conditionals around the command with this syntax:
IF SomeCondition (Command1 | Command2)
If the condition is met then Command1 will run, and its output will be piped to Command2.
The IF command will interpret brackets around a condition as just another character to compare (like # or @) for example:
IF (%_var1%==(demo Echo the variable _var1 contains the text demo
Placing an IF command on the right hand side of a pipe is also possible but the CMD shell is buggy in this area and can swallow one of the delimiter characters causing unexpected results.
A simple example that does work:
Echo Y | IF red==blue del *.log
Chaining IF commands (AND).
The only logical operator directly supported by IF is NOT, so to perform an AND requires chaining multiple IF statements:
IF SomeCondition ( IF SomeOtherCondition ( Command_if_both_are_true ) )
If either condition is true (OR)
This can be tested using a temporary variable:
Set “_tempvar=”
If SomeCondition Set _tempvar=1
If SomeOtherCondition Set _tempvar=1
if %_tempvar% EQU 1 Command_to_run_if_either_is_true
Delimiters
If the string being compared by an IF command includes delimiters such as [Space] or [Comma], then either the delimiters must be escaped with a caret ^ or the whole string must be “quoted”.
This is so that the IF statement will treat the string as a single item and not as several separate strings.
Test Numeric values
IF only parses numbers when one of the compare-op operators (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
This is an important difference because if you compare numbers as strings it can lead to unexpected results: “2” will be greater than “19” and “026” will be less than “10”.
Correct numeric comparison:
IF 2 GEQ 15 echo “bigger”
Using parentheses or quotes will force a string comparison:
IF (2) GEQ (15) echo “bigger”
IF “2” GEQ “15” echo “bigger”
This behaviour is exactly opposite to the SET /a command where quotes are required.
IF should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647)
C:\> if 2147483646 GEQ 2147483647 (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correct
C:\> if 2147483647 GEQ 2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflow
C:\> if -2147483649 GEQ -2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflow
You can perform a string comparison on very long numbers, but this will only work as expected when the numbers are exactly the same length:
C:\> if “2147483647” GEQ “2147483648” (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correct
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
IF does not, by itself, set or clear the Errorlevel.
Examples:
IF EXIST C:\logs\*.log (Echo Log file exists) IF EXIST C:\logs\install.log (Echo Complete) ELSE (Echo failed) IF DEFINED _department ECHO Got the _department variable IF DEFINED _commission SET /A _salary=%_salary% + %_commission% IF CMDEXTVERSION 1 GOTO start_process IF %ERRORLEVEL% EQU 2 goto sub_problem2
IF is an internal command.
- SS64
- CMD
- How-to
Conditionally perform a command.
File syntax IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command) String syntax IF [/I] [NOT] item1==item2 command IF [/I] [NOT] "item1" == "item2" command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command) Error Check Syntax IF [NOT] DEFINED variable command IF [NOT] ERRORLEVEL number command IF CMDEXTVERSION number command key item A text string or environment variable, for more complex comparisons, a variable can be modified using either Substring or Search syntax. command The command to perform. filename A file to test or a wildcard pattern. NOT Perform the command if the condition is false. == Perform the command if the two strings are equal. /I Do a case Insensitive string comparison. compare-op Can be one of: EQU : Equal NEQ : Not equal LSS : Less than < LEQ : Less than or Equal <= GTR : Greater than > GEQ : Greater than or equal >= This 3 digit syntax is used because the > and < symbols are recognised as redirection operators
IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
Compare strings that contain Spaces by using «double quotes»
The IF command can seem flaky if any spaces exist in the comparison strings. for example these commands all seem like they work:
IF ‘ab’ == ‘a b’ Echo OK
IF [ab] == [a b] Echo OKBut if you reverse the logic to see if they are not equal, the code will fail and thow an error:
IF ‘ab’ NEQ ‘a b’ Echo OK
IF [ab] NEQ [a b] Echo OKSimilarly this will fail:
IF ‘a b’ == ‘a b’ Echo OK
The problem with the above, is that single quotes have no special meaning to CMD, so when it reaches a space it assumes that’s the end of the string.
These versions using double quotes will all work:
IF «ab» == «a b» Echo OK
IF «ab» NEQ «a b» Echo OK
IF NOT «ab» == «a b»So then you think, OK I’ll just use double quotes. However there is one remaining gotcha, if the item you are comparing is a quoted filename, so it already contains double quotes, you have an escape sequence:
IF «»long filename»» EQU «something» Echo OK
That will break because the «» acts as an escape. To prevent that from happening strip any quotes from the strings being compared.
In addition to spaces, the above applies to all other delimiters [Comma],[Semicolon], [Equals], [Space] [Tab].
Either the delimiters must be individually escaped with a caret ^ or the whole string must be «quoted».
Test if a variable is empty
To test for the existence of a command line parameter — use empty brackets like this:
IF [%1] == [] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value MissingWhen comparing against a variable that may be empty, we include a pair of brackets [ ] so that if the variable does happen to be empty the IF command still has something to compare: IF [] EQU [] will return True.
You can in fact use almost any character for this a ‘~’ or curly brackets, { } or even the number 4, but square brackets tend to be chosen because they don’t have any special meaning.
When working with filenames/paths you should always surround them with quotes, if %_myvar% contains «C:\Some Path» then your comparison becomes IF [«C:\Some Path»] EQU []
if %_myvar% could contain empty quotes, «» then your comparison should become IF [%_myvar%] EQU [«»]if %_myvar% will never contain quotes, then you can use quotes in place of the brackets IF «%_myvar%» EQU «»
However with this pattern if %_myvar% does unexpectedly contain quotes, you will get IF «»C:\Some Path»» EQU «» those doubled quotes, act as an escape and will break the comparison.
Test if a variable is NULL
In the case of a variable that might be NULL — a null variable will remove the variable definition altogether, so testing for a NULL becomes:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space).
To test for the existence of a variable use SET VariableName, or IF DEFINED VariableName
Test the existence of files and folders
IF EXIST filename Will detect the existence of a file or a folder.
The script empty.cmd will show if the folder is empty or not (this is not case sensitive).
Parenthesis
Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands:
IF EXIST filename.txt ( Echo deleting filename.txt Del filename.txt ) ELSE ( Echo The file was not found. )When combining an ELSE statement with parentheses, always put the opening parenthesis on the same line as ELSE.
) ELSE ( This is because CMD does a rather primitive one-line-at-a-time parsing of the command.When using parentheses the CMD shell will expand [read] all the variables at the beginning of the code block and use those values even if the variables value has just been changed. Turning on DelayedExpansion will force the shell to read variables at the start of every line.
Pipes
When piping commands, the expression is evaluated from left to right, so
IF SomeCondition Command1 | Command2 is equivalent to:
(IF SomeCondition Command1 ) | Command2
The pipe is always created and Command2 is always run, regardless whether SomeCondition is TRUE or FALSEYou can use brackets and conditionals around the command with this syntax:
IF SomeCondition (Command1 | Command2)
If the condition is met then Command1 will run, and its output will be piped to Command2.The IF command will interpret brackets around a condition as just another character to compare (like # or @) for example:
IF (%_var1% == (demo Echo the variable _var1 contains the text demoPlacing an IF command on the right hand side of a pipe is also possible but the CMD shell is buggy in this area and can swallow one of the delimiter characters causing unexpected results.
Chaining IF commands (AND).
The only logical operator directly supported by IF is NOT, so to perform an AND requires chaining multiple IF statements:
IF SomeCondition ( IF SomeOtherCondition ( Command_if_both_are_true ) )
If either condition is true (OR)
This can be tested using a temporary variable:
Set «_tempvar=»
If SomeCondition Set «_tempvar=1»
If SomeOtherCondition Set «_tempvar=1»
if %_tempvar% EQU 1 Command_to_run_if_either_is_true
Test Numeric values
IF only parses numbers when one of the compare-op operators (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.This is an important difference because if you compare numbers as strings it can lead to unexpected results: «2» will be greater than «19» and «026» will be less than «10».
Correct numeric comparison:
IF 2 GEQ 15 echo «bigger»Using parentheses or quotes will force a string comparison:
IF (2) GEQ (15) echo «bigger»
IF «2» GEQ «15» echo «bigger»This behaviour is exactly opposite to the SET /a command where quotes are required.
IF should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647)
C:\> if 2147483646 GEQ 2147483647 (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correctC:\> if 2147483647 GEQ 2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflowC:\> if -2147483649 GEQ -2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflowYou can perform a string comparison on very long numbers, but this will only work as expected when the numbers are exactly the same length:
C:\> if «2147483647» GEQ «2147483648» (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correct
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME% == SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix% == SS6 GOTO they_matched
ERRORLEVEL
There are two different methods of checking an errorlevel, the first syntax ( IF ERRORLEVEL … ) provides compatibility with ancient batch files from the days of Windows 95.
The second method is to use the %ERRORLEVEL% variable available in Windows 2000 or newer.IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE whether the errorlevel is 0, 1 or 5 or 64
IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64
IF NOT ERRORLEVEL 1 means if ERRORLEVEL is less than 1 (Zero or negative).
This is not very readable or user friendly and does not easily account for negative error numbers.Using the %ERRORLEVEL% variable is a more logical method of checking Errorlevels:
IF %ERRORLEVEL% NEQ 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error foundIF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was foundThis allows you to trap errors that can be negative numbers, you can also test for specific errors:
IF %ERRORLEVEL% EQU 64 …To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will override and prevent the system variable %ERRORLEVEL% from being read by commands such as ECHO and IF.
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
In early versions of Windows NT/XP comparisons made using == would include the spaces before and after the ==, so for backwards compatibility you may still see commands written as IF alpha==beta rather than IF alpha == beta
IF does not, by itself, set or clear the Errorlevel.
IF is an internal command.
Examples
Does a specific file exist:
IF EXIST C:\logs\install.log (Echo Complete) ELSE (Echo failed)
Does any file exist:
IF EXIST C:\logs\*.log (Echo Log file exists)
Does a variable exist:
IF DEFINED _department ECHO This is for %_department%.
IF DEFINED _commission SET /A «_salary=%_salary% + %_commission%»
Do we have Command Processor Extensions set?
IF CMDEXTVERSION 2 GOTO start_process
Does an error exist:
IF %ERRORLEVEL% EQU 2 goto sub_problem2
You see things; and you say ‘Why?’ But I dream things that never were; and I say ‘why not?’ ~ George Bernard Shaw
Related commands
Using parentheses to group and expand expressions.
Conditional execution syntax (AND / OR)
SET — Display or Edit environment variables.
ECHO — Display message on screen.
EXIT — Set a specific ERRORLEVEL.
IFMEMBER — group member (Resource kit).
SC — Is a Service running (Resource kit).
Equivalent PowerShell: IF — Conditionally perform a command.
Equivalent bash command (Linux):
if — Conditionally perform a command.
Copyright © 1999-2025 SS64.com
Some rights reserved