Булева логика в пакетных файлах

The batch language is equipped with a full set of boolean logic operators like AND, OR, XOR, but only for binary numbers, not for conditions.
Neither are there any values for TRUE or FALSE.
The only logical operator available for conditions is the NOT operator.

This page will teach you how to emulate the missing logical operators.

The basics

To test if a condition is true, IF is used:

The AND operator

The AND operator is the easiest one to emulate: we can just “nest” IF statements.

Even though the three code snippets are identical, we will use the first one for better readability, especially when the equation becomes more complex.

An example: if %1 must be less than 10 AND %2 must be greater than 0, and we want to include an ELSE statement in case these conditions are not both true, the need for parenthesis becomes obvious.

Consider these two code snippets:

The placement of the ELSE statement is critical!

The code snippet above still does not cover the case when %1 is greater than or equal to 10.
To complete it, we would need:

Unlike the simple basic example, to convert these code snippets to one-liners again is impossible without parenthesis.
You may often be tempted to remove some parenthesis, but this may change the logic of the equation.

The OR operator

Often the OR operator can be replaced by AND and NOT operaters: if condition 1 OR condition 2 must be true, you may also say that NOT condition 1 AND NOT condition must be false.
An example: we want to replace the AND operator in the previous example by the OR operator, i.e. %1 must be less than 10 OR %2 must be greater than 0.
For numerical comparisons we don’t need NOT but we can replace LSS by GEQ etcetera.
We might try:

The XOR operator

Though possible, emulating the XOR operator with the techniques described before would require far too complex code snippets, a debugger’s nightmare.

Alternatives

There are two alternative techniques:

Temporary variables for the result

This technique is perfect for both the AND and the OR operator.
OR:

Consider using 4 conditions, and compare the complexity of the techniques described so far.

To emulate XOR for 2 conditions you can use SET Result += 1 and IF %Result% EQU 1 instead.

Temporary variables per condition, combined with binary math

For this technique, use a (binary) variable for each condition:

IF %1 LSS 10 (SET Cond1=1) ELSE (SET Cond1=0)
IF %2 GTR 0 (SET Cond2=1) ELSE (SET Cond2=0)

Next, use binary math to get the results:

Summary

We have discussed techniques for binary logic in batch files.
Though there is a full set of operators available for binary math, they are lacking for logical conditions.
This page shows how to translate these conditions to 0 (FALSE) or 1 (TRUE) and use binary math to get the logical results.

page last modified: 2011-03-04

Время на прочтение

Недавно я вырос из лютого эникея в очень большой компании, до скромного сисадмина надзирающего за сетью в 10 ПК. И, как очень ленивый сисадмин, столкнулся с задачами по автоматизации своей деятельности. Полгода назад я еще не знал, что в командной строке Windows есть конвейеры. Это стало первым шокирующим открытием. И я пошел дальше, и выяснилось, что там, где я раньше писал утилитки на C#, Delphi или громоздкие скрипты с вложенными циклами, можно было обойтись парой команд forfiles или robocopy.
Не буду рассказывать о банальностях, типа о перечислении файлов и папок клавишей Tab. Под хабракатом расскажу о том, что может быть полезно начинающим админам и эникеям.

:/>  Список псевдонимов
Горячие клавиши

Начнем с горячих клавиш, ведь сначала необходимо изучить, что нам может дать рабочая среда.

то после нажатия комбинации клавиш F2 + 5 вы получите:

F3 — Выводит последнюю, и только последнюю, в истории команду целиком. F5 — Выводит последние введенные команды по порядку, также как и стрелка вверх. F6 — Вставляет символ EOF на текущую позицию командной строки, что аналогично нажатию комбинации Ctrl + Z. F7 — Диалоговое окно, содержащее историю команд.


Булева логика в пакетных файлах

Операторы командной строки

Я, давным-давно, когда был маленький, даже не представлял как можно работать в консоли без графического интерфейса. Ведь вывод команд порой занимает десятки страниц, а если надо выбрать оттуда какие-то данные, то и постраничный вывод не спасет. Но однажды я поставил на старый комп FreeBSD, открыл хандбук и просто голова кругом пошла от открывшихся возможностей. Там можно перенаправить вывод команды на вход другой команды и это называется конвейером.

Оператором конвейера в *nix и cmd, является символ вертикальной черты.

Например, вывод всех текстовых файлов в текущей папке покажет команда

Оператор объединения команд

Пример: Команда1 & Команда2 – сначала выполнятся Команда1, а уже потом Команда2

Оператор И

Пример: Команда1 && Команда2 — Команда2 будет выполняться только в том случае, если произошло успешное выполнение Команды1

Оператор ИЛИ

Для группирования команд используются круглые скобки, примеры:

UPD1

Для тех, кто не в теме, циркумфлекс(вот этот знак “^”) означает нажатие клавиши с Ctrl(^C = Ctrl +C).

P. S. Другие тонкости командной строки Windows, уже неоднократно освещались на Хабре. И не вижу смысла копи-пастить.
P. P. S. Ссылки на интересные посты и статьи по другим возможностям командной строки Windows:
Ввод-вывод, циклы, переменные
Работа с массивами
Интереснейший топик по теме

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.

Using the variable is a more logical method of checking Errorlevels:

To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.

Test if a variable is empty

if will never contain quotes, then you can use quotes in place of the brackets IF “%_myvar%” EQU “”
However with this pattern if 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 DEFINED will return true if the variable contains any value (even if the value is just a space).

:/>  Add a Language Pack Online

To test for the existence of a variable use , 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

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

You can use brackets and conditionals around the command with this syntax:

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:

Chaining IF commands (AND).

The only logical operator directly supported by is , so to perform an 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 only parses numbers when one of the 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”.

This behaviour is exactly opposite to the SET /a command where quotes are required.

should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647)

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:

Wildcards

Wildcards are not supported by IF, so 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 will be disabled.

IF does not, by itself, set or clear the Errorlevel.

Examples

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

Related commands

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

Or the converse:

Both the true condition and the false condition:

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)

IF NOT DEFINED var (SET var=default value)

:/>  Загрузка BIOS с диска и настройка BIOS ноутбука Dell Inspiron 15 для установки операционной системы WINDOWS 7, 8 с USB-накопителя или диска

Checking If a Variable Matches a Text String

Or with a case insensitive comparison

Artimetic Comparisons

If (condition) (do_something) ELSE (do_something_else)


Булева логика в пакетных файлах

Checking Variables

Just like the ‘if’ statement in Batch Script, the if-else can also be used for checking variables which are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both strings and numbers.

Checking Integer Variables

The key thing to note about the above program is −

“The value of variable c is 15”
“Unknown value”

Checking String Variables

“The value of variable String1”
“Unknown value”

Checking Command Line Arguments

If the above code is saved in a file called test.bat and the program is executed as

test.bat 1 2 4

1
2
4
“The value is 1”
“The value is 2”
“Unknown value”

If defined

if defined somevariable somecommand

“Variable str1 is defined”
“Variable str3 is not defined”

If exists

If exist somefile.ext do_something

“File exists”
“File does not exist”

Бывает, что при написании командного файла (пакетного файла, bat файла, cmd файла) требуется записать в условном операторе IF более сложное условие, составленное с помощью операторов И и ИЛИ.

Как известно, bat файлы не имеют таких логических операторов, поэтому в них нельзя написать конструкции типа:

Эта статья рассказывает, как в bat файле реализовать логику операторов И / ИЛИ другими доступными способами.

Надо сказать, что всё-таки командные файлы Windows предназначены для пакетного выполнения консольных команд, и задачи по расчету или обработке данных лучше писать в скриптах (PowerShell, WSH / JScript / VBScript), вызывая их из bat файла.

Ссылки для скачивания файлов находятся в конце статьи.

Самый простой вариант – вложенное выполнение двух операторов IF:

То есть вместо and мы просто пишем if. Можно использовать не только проверку значения переменной, но и проверку наличия файла. Условий может быть больше двух.

Оператор IF с логическим ИЛИ (OR) в bat файле

С оператором OR так просто не получится, причем есть разные способы.

Способ 1 – через последовательные ИЛИ

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

В примере ниже значение переменной a сравнивается с тремя значениями, и для любого из value1, value2, value3 условие будет выполнено. А если задать a какое-то другое значение, например, set a=value4, то условие выполнено не будет, что нам и нужно:

Способ 2 — через И и НЕ

Этот способ основан на том факте, что логическую операцию ИЛИ можно представить через операции И и НЕ, например, a OR b эквивалентно NOT ( NOT A AND NOT B ). Оператор NOT уже есть в bat файлах, а оператор AND можно представить через последовательные IF, как мы видели выше.

Поэтому тот же результат можно получить по-другому:

Этот способ занимает немного меньше строк, чем предыдущий.