Windows cmd if else if

Rob van der Woude's Scripting Pages

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
command2
command1 && command2 Execute command2 only if execution of command1 has finished successfully command1
IF %ErrorLevel% EQU 0 command2
command1 || command2 Execute command2 only if execution of command1 has finished unsuccessfully command1
IF %ErrorLevel% NEQ 0 command2
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:
(
    command1
    command2
) && (
    command3
) && (
    command4
) || (
    ECHO Error
)

Thanks Darin


page last modified: 2022-03-23; loaded in 0.0020 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

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

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

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

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

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

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

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

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.

На чтение 5 мин Просмотров 10.7к. Опубликовано

В этой статье мы рассмотрим условный оператор 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, то круглые скобки необходимы.

if командная строка

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

@echo off
if"%1"=="1"(echo odin) else (echo dva)

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

@echo off
if"%1"=="1"(hostname & ver & ipconfig /all) else (netstat -a)

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

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

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

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

@echo off
set Var1=100
if defined Var1 (echo%Var1%)
set Var1=
if not defined Var1 (echo NOT EXIST!!! Var1)

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

100
NOT EXIST!!! Var1

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

cmd if

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

@echo off
if"%1"=="1"(@if"%2"=="2"(hostname & ver) else (ver)) else (hostname & ver & netstat -a)

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

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

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

@echo off
if"%1"=="slovo"(echo slovo) else (@if "%1"=="SLOVO"(echo SLOVO) else (echo NOT DATA!!!))

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

@echo off
if/I "%1"=="slovo"(echo slovo) else (if/I "%1"=="SLOVO"(echo SLOVO) else (echo NOT DATA!!!))

В данном случае, передадим мы строку 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
cmd if else

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

  • 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 >>

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Sketchup make для windows
  • Настройка двух сетевых карт на одном компьютере windows 10
  • Lp cab windows server 2016
  • Как выйти из полноэкранного режима на компьютере на клавиатуре windows 10
  • Vs code stm32 настройка windows