Windows cmd if block

Урок 5 по CMD — условный оператор if

В этой статье мы рассмотрим условный оператор if командной строки (CMD). Как и в любом другом языке программирования, условные оператор служит для проверки заданного условия и в зависимости от результат, выполнять то, или иное действие.

Условный оператор cmd if содержит практически тот же синтаксис, что и аналогичные конструкции языков VBScript (смотри статью “Урок 5 по VBScript: Условный оператор if. else и select. case”) и Jscript (статья “Урок 8 по JScript: Описание условного оператора if. else, арифметических и логических операторов”) сервера сценариев Windows Script Host.

Оператор if командная строка

if условие (оператор1) [else (оператор2)]

Вначале идет проверка условия, если оно выполняется, идет переход к выполнению оператора1, если нет – к оператору2. Если после ключевого слова if прописать not (if not), то: произойдет проверка условия, если оно не выполниться – переход к оператору1, если условие выполняется – переход к оператору2. Использование круглых скобок не является обязательным, но если вам нужно после проверки условия выполнить сразу несколько операторов cmd if, то круглые скобки необходимы.

Давайте откроем редактор notepad++ и пропишем в нем такой код:

Как я уже сказал, мы можем использовать не один оператор (командной строки) cmd if, а несколько, посмотрите на данный пример:

Тут, как и прежде идет проверка передаваемого сценарию параметра, если значение равно 1, то произойдет последовательное выполнение трех команд:

  • hostname – выводит имя компьютера
  • ver – выводит версию ОС
  • ipconfig /all – выводит настройки сети

Для последовательного выполнения команд мы использовали знак конкатенации (объединения) “&”. При невыполнении условия произойдет вызов утилиты netstat.

Что бы проверить существование переменной, используются операторы if defined (если переменная существует) и if not defined (если переменная не существует):

Если вы запустите на выполнение данный код, то в окне командной строки будут выведены две строки:

100
NOT EXIST. Var1

Вначале, в сценарии происходит создание переменной Var1 и присвоение ей значения 100, далее идет проверка: если переменная Var1 существует, вывести ее значение. Потом мы удаляем переменную и снова запускаем проверку: если переменная Var1 не существует, вывести строку NOT EXIST. Var1.

Мы вправе использовать условный оператор if как вложенный:

В данном примере, первый оператор командной строки if проверяет, равен ли первый аргумент 1, если да, то идет выполнение второго условно оператора и проверка на значение другого аргумента.

Обратите внимание. Все переменные определяются как строки. При проверке условия я заключал имена переменных и значений в двойные кавычки, это позволяет избежать ошибок, так как параметры или аргументы могут содержать пробелы, или же у переменной может и вовсе отсутствовать значение.

Давайте теперь посмотрим на такой пример:

Тут идет проверка первого аргумента, и регистр строки учитывается, что бы отключить учет регистра при проверке строк, после оператора if нужно прописать ключ /I:

В данном случае, передадим мы строку SLOVO, slovo, SloVo и так далее, все ровно на экран консоли выведется строка “slovo”, так как учет регистра знаков будет отключен.

Оператор if командная строка, операторы сравнения

Кроме оператора сравнения “==” можно использовать и другие операторы для проверки условия:

  • equ «Равно». Дает True, если значения равны
  • neq «Не равно». Дает True, если значения не равны
  • lss «Меньше». Дает True, если зпачение1 меньше, чем значение2
  • lcq «Меньше или равно». Дает True, если значепие1 равно или меньше, чемзначение2
  • gtr «Больше». Дает True, если значение1 больше, чем значение2
  • geq «Больше или равно». Дает True, если значепие1 равно или больше, чем значение2

В этой статье мы рассмотрели условный оператор командной строки if.

Спасибо за внимание. Автор блога Владимир Баталий

if if

Выполняет условную обработку в пакетных программах. Performs conditional processing in batch programs.

Читайте также:  Есть архиватор для mac os

Синтаксис Syntax

Если расширения команд включены, используйте следующий синтаксис: If command extensions are enabled, use the following syntax:

Параметры Parameters

Параметр Parameter Описание Description
not not Указывает, что команда должна выполняться, только если условие имеет значение false. Specifies that the command should be carried out only if the condition is false.
ERRORLEVEL errorlevel Задает истинное условие, только если предыдущая программа, выполненная Cmd.exe, вернула код выхода, который больше или равен Number. Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
Указывает команду, которая должна быть выполнена при выполнении предыдущего условия. Specifies the command that should be carried out if the preceding condition is met.
== Задает истинное условие, только если строка1 и строка2 совпадают. Specifies a true condition only if string1 and string2 are the same. Эти значения могут быть строками литерала или пакетными переменными (например, %1 ). These values can be literal strings or batch variables (for example, %1 ). Литеральные строки не нужно заключать в кавычки. You do not need to enclose literal strings in quotation marks.
существующие exist Указывает истинное условие, если указанное имя файла существует. Specifies a true condition if the specified file name exists.
Задает оператор сравнения из трех букв, включая: Specifies a three-letter comparison operator, including:
  • Равно — равно EQU — Equal to
  • Нек — не равно NEQ — Not equal to
  • ЛСС — меньше LSS — Less than
  • LEQ -меньше или равно LEQ — Less than or equal to
  • ГТР — больше GTR — Greater than
  • Жек — больше или равно GEQ — Greater than or equal to
/i /i Принудительное сравнение строк не учитывает регистр. Forces string comparisons to ignore case. Параметр /i можно использовать в string1==string2 формате If. You can use /i on the string1==string2 form of if. Эти сравнения являются универсальными, в том случае, если и строка1 , и строка2 состоят из цифр, строки преобразуются в числа и выполняется числовое сравнение. These comparisons are generic, in that if both string1 and string2 are comprised of numeric digits only, the strings are converted to numbers and a numeric comparison is performed.
кмдекстверсион cmdextversion Задает истинное условие, только если внутренний номер версии, связанный с компонентом расширения команд Cmd.exe, равен или больше указанного числа. Specifies a true condition only if the internal version number associated with the command extensions feature of Cmd.exe is equal to or greater than the number specified. Первая версия — 1. The first version is 1. Он увеличивается на единицу при добавлении значительных улучшений в расширения команд. It increases by increments of one when significant enhancements are added to the command extensions. Кмдекстверсион Conditional не имеет значения true, если расширения команд отключены (по умолчанию расширения команд включены). The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined defined Указывает истинное условие, если переменная определена. Specifies a true condition if variable is defined.
Задает команду командной строки и все параметры, которые будут переданы команде в предложении else . Specifies a command-line command and any parameters to be passed to the command in an else clause.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Комментарии Remarks

Если условие, указанное в предложении If , имеет значение true, выполняется команда, следующая за условием. Если условие имеет значение false, команда в предложении If игнорируется и команда выполняет любую команду, указанную в предложении else . If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause.

Когда программа останавливается, она возвращает код выхода. When a program stops, it returns an exit code. Чтобы использовать коды выхода в качестве условий, используйте параметр ERRORLEVEL . To use exit codes as conditions, use the errorlevel parameter.

При использовании определенного значения в среду добавляются следующие три переменные: % ERRORLEVEL%, % кмдкмдлине% и % кмдекстверсион%. If you use defined, the following three variables are added to the environment: %errorlevel%, %cmdcmdline%, and %cmdextversion%.

% ERRORLEVEL%: разворачивается в строковое представление текущего значения переменной среды ERRORLEVEL. %errorlevel%: Expands into a string representation of the current value of the ERRORLEVEL environment variable. Эта переменная предполагает, что отсутствует существующая переменная среды с именем ERRORLEVEL. This variable assumes that there isn’t already an existing environment variable with the name ERRORLEVEL. Если это так, вместо него будет получено значение ERRORLEVEL. If there is, you’ll get that ERRORLEVEL value instead.

% кмдкмдлине%: разворачивается в исходную командную строку, которая была передана Cmd.exe до любой обработки Cmd.exe. %cmdcmdline%: Expands into the original command line that was passed to Cmd.exe prior to any processing by Cmd.exe. Предполагается, что отсутствует существующая переменная среды с именем КМДКМДЛИНЕ. This assumes that there isn’t already an existing environment variable with the name CMDCMDLINE. Если это так, вы получите вместо этого значение КМДКМДЛИНЕ. If there is, you’ll get that CMDCMDLINE value instead.

% кмдекстверсион%: разворачивается в строковое представление текущего значения кмдекстверсион. %cmdextversion%: Expands into the string representation of the current value of cmdextversion. Предполагается, что отсутствует существующая переменная среды с именем КМДЕКСТВЕРСИОН. This assumes that there isn’t already an existing environment variable with the name CMDEXTVERSION. Если это так, вы получите вместо этого значение КМДЕКСТВЕРСИОН. If there is, you’ll get that CMDEXTVERSION value instead.

Предложение else необходимо использовать в той же строке, что и команда после оператора If. You must use the else clause on the same line as the command after the if.

Примеры Examples

Чтобы отобразить сообщение не удается найти файл данных если не удается найти файл Product. dat, введите: To display the message Cannot find data file if the file Product.dat cannot be found, type:

Чтобы отформатировать диск в диске а и вывести сообщение об ошибке при возникновении ошибки в процессе форматирования, введите в пакетный файл следующие строки: To format a disk in drive A and display an error message if an error occurs during the formatting process, type the following lines in a batch file:

Чтобы удалить файл Product. dat из текущего каталога или отобразить сообщение, если Product. dat не найден, введите в пакетном файле следующие строки: To delete the file Product.dat from the current directory or display a message if Product.dat is not found, type the following lines in a batch file:

Эти строки можно объединить в одну строку следующим образом: These lines can be combined into a single line as follows:

Чтобы вывести значение переменной среды ERRORLEVEL после выполнения пакетного файла, введите в пакетный файл следующие строки: To echo the value of the ERRORLEVEL environment variable after running a batch file, type the following lines in the batch file:

Чтобы вернуться к метке «хорошо», если значение переменной среды ERRORLEVEL меньше или равно 1, введите: To go to the okay label if the value of the ERRORLEVEL environment variable is less than or equal to 1, type:

Windows cmd if block

Performs conditional processing in batch programs.

Syntax

If command extensions are enabled, use the following syntax:

Parameters

Parameter Description
not Specifies that the command should be carried out only if the condition is false.
errorlevel Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
Specifies the command that should be carried out if the preceding condition is met.
== Specifies a true condition only if string1 and string2 are the same. These values can be literal strings or batch variables (for example, %1 ). You do not need to enclose literal strings in quotation marks.
exist Specifies a true condition if the specified file name exists.
Specifies a three-letter comparison operator, including:
  • EQU — Equal to
  • NEQ — Not equal to
  • LSS — Less than
  • LEQ — Less than or equal to
  • GTR — Greater than
  • GEQ — Greater than or equal to
/i Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2 are comprised of numeric digits only, the strings are converted to numbers and a numeric comparison is performed.
cmdextversion Specifies a true condition only if the internal version number associated with the command extensions feature of Cmd.exe is equal to or greater than the number specified. The first version is 1. It increases by increments of one when significant enhancements are added to the command extensions. The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined Specifies a true condition if variable is defined.
Specifies a command-line command and any parameters to be passed to the command in an else clause.
/? Displays help at the command prompt.

Remarks

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause.

When a program stops, it returns an exit code. To use exit codes as conditions, use the errorlevel parameter.

If you use defined, the following three variables are added to the environment: %errorlevel%, %cmdcmdline%, and %cmdextversion%.

%errorlevel%: Expands into a string representation of the current value of the ERRORLEVEL environment variable. This variable assumes that there isn’t already an existing environment variable with the name ERRORLEVEL. If there is, you’ll get that ERRORLEVEL value instead.

%cmdcmdline%: Expands into the original command line that was passed to Cmd.exe prior to any processing by Cmd.exe. This assumes that there isn’t already an existing environment variable with the name CMDCMDLINE. If there is, you’ll get that CMDCMDLINE value instead.

%cmdextversion%: Expands into the string representation of the current value of cmdextversion. This assumes that there isn’t already an existing environment variable with the name CMDEXTVERSION. If there is, you’ll get that CMDEXTVERSION value instead.

You must use the else clause on the same line as the command after the if.

Examples

To display the message Cannot find data file if the file Product.dat cannot be found, type:

To format a disk in drive A and display an error message if an error occurs during the formatting process, type the following lines in a batch file:

To delete the file Product.dat from the current directory or display a message if Product.dat is not found, type the following lines in a batch file:

These lines can be combined into a single line as follows:

To echo the value of the ERRORLEVEL environment variable after running a batch file, type the following lines in the batch file:

To go to the okay label if the value of the ERRORLEVEL environment variable is less than or equal to 1, type:

Читайте также:  Windows cannot format exfat
Оцените статью