Availability
The if command is an internal command accessed and used in batch files.
Chaining if commands (and).
The only logical operator directly supported by IF is NOT , so to perform an AND requires chaining multiple IF statements:
Checking if a variable is not set
IF "%var%"=="" (SET var=default value)IF NOT DEFINED var (SET var=default value)Checking integer variables
The following example shows how the ‘if’ statement can be used for numbers.
Example
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.
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 defined
A special case for the ‘if’ statement is the “if defined”, which is used to test for the existence of a variable. Following is the general syntax of the statement.
if defined somevariable somecommand
Following is an example of how the ‘if defined’ statement can be used.
Example
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
If exists
Another special case for the ‘if’ statement is the “if exists “, which is used to test for the existence of a file. Following is the general syntax of the statement.
If exist somefile.ext do_something
Following is an example of how the ‘if exists’ statement can be used.
Example
Parenthesis
Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands:
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.
Pipes
When piping commands, the expression is evaluated from left to right, so
IF SomeConditionCommand1 | Command2 is equivalent to:
(IF SomeConditionCommand1 ) | Command2The 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.
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”.
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.
IF is an internal command.
You see things; and you say ‘Why?’ But I dream things that never were; and I say ‘why not?’
George Bernard Shaw
Windows xp and earlier syntax
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command IF [NOT] string1==string2 command IF [NOT] EXIST filename command
Примеры
Если файл Product.dat не удается найти, появится следующее сообщение:
Если в приведенном ниже примере при форматировании диска в дисководе A возникнет ошибка, будет выведено сообщение об ошибке:
Если ошибка не возникнет, сообщение об ошибке выведено не будет.
Команда if не может быть использована непосредственно для проверки существования каталога, но в каждом каталоге существует устройство (NUL). Следовательно, существование каталога может быть проверено, как показано ниже. В следующем примере проверяется наличие каталога:
Для вопросов, обсуждений, замечаний, предложений и т. п. можете использовать раздел форума этого сайта (требуется регистрация).
Conditionally perform a command.
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.
Расшифровка значений
not
Предусматривает, что исполнение станет осуществляться только в той ситуации, когда заданные условия не будут реализовываться.
errorlevel заданное_число
Исполнение происходит в той ситуации, когда результатом обработки предыдущей команды стал код, значение которого превышает или равняется заданному числу.
команда_для_обработки
Позволяет задать команду для обработки в том случае, если происходит соблюдение указанных условий.
строка_№1==строка_№2
Данный параметр устанавливает требование – условие станет выполняться только в том случае, когда указанные строки будут совпадать друг с другом. Допускается несколько вариантов задания строк, в зависимости от конкретной ситуации.
exist название_файла
Данное условие будет выполнено в том случае, когда документ с указанным именем существует.
оператор_сравнения
В качестве указанного параметра предусматривается оператор сравнения. Он состоит из трех символов и необходимо сказать о доступных вариантах: EQU (равенство), NEQ (значения не равны между собой), LSS (менее), GTR (более), LEQ (значение является меньшим или равным), GEQ (значение является большим или равным).
Проводится сравнение между строками. Основной особенностью параметра является то, что подобный процесс осуществляется без учета строчных заглавных символов.
cmdextversion заданное_число
Требует выполнять равнение между версиями. Здесь предусматривается, что заданное число будет увеличиваться на единицу каждый раз, когда осуществляется внесение крупных корректировок. Таким образом, условие станет выполняться, только когда номер внутренней версии будет равен или превышать указанное значение.
defined заданная_переменная
Выполнение условия осуществляется в том случае, когда точно определена заданная переменная.
команда_и_параметры
Команда, а также все доступные для неё параметры в ходе обработки в КС, когда работает else.
Синтаксис
if [not] errorlevel заданное_число команда_для_обработки [else выражение] if [not] строка_№1==строка_№2 команда_для_обработки [else выражение] if [not] exist название_файла команда_для_обработки [else выражение]
В том случае, когда расширения командного процессора являются допустимыми, необходимо применять указанный ниже вариант:
if [/i] строка_№1 оператор_сравнения строка_№2 команда_для_обработки [else выражение] ifcmdextversion заданное_число команда_для_обработки [else выражение] ifdefined заданная_переменная команда_для_обработки [else команда_и_параметры]



