IF - Execute a command if a condition is true
Purpose: Execute a command if a condition or set of conditions is
true.
Format: IF [NOT] condition [.AND. | .OR. | .XOR. [NOT] condition ...]
command
condition : A test or set of tests to determine if the
command should be executed.
command : The command to execute if the condition is true.
See also: IFF, @IF.
Usage
IF is normally used only in aliases and batch files. It is always
followed by one or more conditions and then a command. First, the
conditions are evaluated. If they are true, the command is executed.
Otherwise, the command is ignored. If you add a NOT before a condition,
the command is executed only when the condition is false.
You can link conditions with .AND., .OR., or .XOR., and you can group
conditions with parentheses (see Combining Tests below). You can also
nest IF statements.
The conditions can test strings, numbers, the existence of a file or
subdirectory, the exit code returned by the preceding external command,
and the existence of aliases and internal commands.
The command can be an alias, an internal command, an external command, or
a batch file. The entire IF statement, including all conditions and the
command, must fit on one line.
Some examples of IF conditions and commands are included below;
additional examples can be found in the EXAMPLES.BTM file which came with
CMD.EXE.
You can use command grouping to execute multiple commands if the
condition is true. For example, the following command tests if any .TXT
files exist. If they do, they are copied to drive A: and their
extensions are changed to .TXO :
if exist *.txt (copy *.txt a: & ren *.txt *.txo)
(Note that the IFF command provides a more structured method of executing
multiple commands if a condition or set of conditions is true.)
When an IF test fails, the remainder of the command is discarded, and the
command processor normally continues with the next command on the line,
or the next line. This behavior is not compatible with CMD.EXE, which
discards all remaining commands on the line when an IF test fails,
including those after a command separator or pipe character. To change
the behavior so that IF affects all commands on the line, as in CMD.EXE,
set DuplicateBugs to Yes in CMD.INI.
For example, if DuplicateBugs is set to Yes (the default), the following
command will display nothing, because the second ECHO command is
discarded along with the first when the condition fails. If
DuplicateBugs is set to No, it will display "hello":
[c:\] if 1 == 2 echo Wrong! & echo hello
Conditions
The conditional tests listed in the following sections are available in
both the IF and IFF commands. They fit into two categories: string and
numeric tests, and status tests. The tests can use environment
variables, internal variables and variable functions, file names, literal
text, and numeric values as their arguments.
String and Numeric Tests
Six test conditions can be used to test character strings. The same
conditions are available for both numeric and normal text strings (see
below for details). In each case you enter the test as:
string1 operator string2
The operator defines the type of test (equal, greater than or equal, and
so on). You should always use spaces on both sides of the operator The
operators are:
EQ or == string1 equal to string2
NE or != string1 not equal to string2
LT string1 less than string2
LE string1 less than or equal to string2
GE string1 greater than or equal to string2
GT string1 greater than string2
When IF compares two character strings, it will use either a numeric
comparison or a string comparison. A numeric comparison treats the
strings as numeric values and tests them arithmetically. A string
comparison treats the strings as text.
The difference between numeric and string comparisons is best explained
by looking at the way two values are tested. For example, consider
comparing the values 2 and 19. Numerically, 2 is smaller, but as a
string it is "larger" because its first digit is larger than the first
digit of 19. So the first of these conditions will be true, and the
second will be false:
if 2 lt 19 ...
if "2" lt "19" ...
IF determines which kind of test to do by examining the first character
of each string. If both strings begin with a numeric character (a digit,
sign, or decimal separator), a numeric comparison is used. (If a string
begins with a decimal separator it is not considered numeric unless the
next character is a digit, and there are no more decimal separators
within the string. For example, ".07" is numeric, but ".a" and ".07.01"
are not.) If either value is non-numeric, a string comparison is used.
To force a string comparison when both values are or may be numeric, use
double quotes around the values you are testing, as shown above. Because
the double quote is not a numeric character, IF performs a string
comparison.
Case differences are ignored in string comparisons. If two strings begin
with the same text but one is shorter, the shorter string is considered
to be "less than" the longer one. For example, "a" is less than "abc",
and "hello_there" is greater than "hello".
When you compare text strings, you should always enclose the arguments in
double quotes in order to avoid syntax errors which may occur if one of
the argument values is empty.
Numeric comparisons work with both integer and decimal values. The
values to be compared must contain only numeric digits, decimal points,
and an optional sign (+ or -). The number may contain up to 16 digits to
the left of the decimal point, and 8 digits to the right.
Internal variables and variable functions are very powerful when combined
with string and numeric comparisons. They allow you to test the state of
your system, the characteristics of a file, date and time information, or
the result of a calculation. You may want to review the variables and
variable functions when determining the best way to set up an IF test.
This batch file fragment runs a program called MONOPROG if a monochrome
monitor is attached to the system:
if "%_monitor" == "mono" monoprog
This batch file fragment tests for a string value:
input "Enter your selection : " %%cmd
if "%cmd" == "WP" goto wordproc
if "%cmd" NE "GRAPHICS" goto badentry
This example calls GO.BTM if the first two characters in the file MYFILE
are "GO":
if "%@left[2,%@line[myfile,0]]" == "GO" call go.btm
Status Tests
These conditions test the system or command processor status. You can
use internal variables and variable functions to test many other parts of
the system status.
DEFINED variable
Ifthevariableexistsintheenvironment ,theconditionistrue . This
isequivalenttotestingwhetherthevariableisnotempty
,forexamplethefollowingtwocommandsareequivalent :
if defined abc echo Hello
if "%abc" != "" echo Hello
ERRORLEVEL [operator] n
Thistestretrievestheexitcodeoftheprecedingexternalprogram . By
convention
,
programs
return
an
exit
code
of0whentheyaresuccessfulandanumberbetween1and255toindicateanerror(
dependingontheprogramyouarerunning
,themaximumreturnvaluemaybelarger ) . The
conditioncanbeanyoftheoperatorslistedabove( EQ ,! = ,GT ,etc . ) . If
nooperatorisspecified ,thedefaultisGE . The
comparisonisdonenumerically .
Not all programs return an explicit exit code. For programs which
do not, the behavior of ERRORLEVEL is undefined.
EXIST filename
Ifthefileexists ,theconditionistrue . You
canusewildcardsinthefilename
,
in
whichcasetheconditionistrueifanyfilematchingthewildcardnameexists
.
Do not use IF EXIST to test for existence of a directory (use IF
ISDIR instead). Due to variations in operating system internals,
IF EXIST will not return consistent results when used to test for
the existence of a directory.
ISALIAS aliasname
Ifthenameisdefinedasanalias ,theconditionistrue .
ISDIR | DIREXIST path
Ifthesubdirectoryexists ,theconditionistrue .
ISINTERNAL command
Ifthespecifiedcommandisanactiveinternalcommand ,theconditionistrue
. CommandscanbeactivatedanddeactivatedwiththeSETDOS/ Icommand .
ISLABEL label
Ifthespecifiedlabelexistsinthecurrentbatchfile ,theconditionistrue
. Labelsmaybeoneormorewordslong .
This batch file fragment tests for the existence of A:\JAN.DOC before
copying it to drive C (this avoids an error message if the file does not
exist):
if exist a:\jan.doc copy a:\jan.doc c:\
This example tests the exit code of the previous program and stops all
batch file processing if an error occurred:
if errorlevel == 0 goto success
echo "External Error -- Batch File Ends!"
cancel
Combining Tests
You can negate the result of any test with NOT, and combine tests of any
type with .AND., .OR., and .XOR.
When two tests are combined with .AND., the result is true if both
individual tests are true. When two tests are combined with .OR., the
result is true if either (or both) individual tests are true. When two
tests are combined with .XOR., the result is true only if one of the
tests is true and the other is false.
This example runs a program called HIGHRES if either an EGA or VGA video
adapter is in use. Enter this on one line:
if "%_video" == "EGA" .or. "%_video" == "vga" highres
Test conditions are always scanned from left to right there is no
implied order of precedence, as there is in some programming languages.
You can, however, force a specific order of testing by grouping
conditions with parentheses, for example (enter this on one line):
if (%a == 1 .or. (%b == 2 .and. %c == 3)) echo something
Parentheses can only be used when the portion of the condition inside the
parentheses contains at least one ".and.", ".or.", or ".xor.".
Parentheses on a simple condition which does not combine two or more
tests will be taken as part of the string to be tested, and will probably
make the test fail. For example, the first of these IF tests would fail;
the second would succeed:
if (a == a) ...
if (a == a .and. b == b) ...
Created using Inf-PHP v.2 (c) 2003 Yuri Prokushev
Created using Inf-HTML v.0.9b (c) 1995 Peter Childs