Windows bat if else if

I have a question about if — else structure in a batch file. Each command runs individually, but I couldn’t use «if — else» blocks safely so these parts of my programme doesn’t work. How can I do make these parts run? Thank you.

IF %F%==1 IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )
ELSE IF %F%==1 IF %C%==0 (
    ::moving the file c to d
    move "%sourceFile%" "%destinationFile%"
    )

ELSE IF %F%==0 IF %C%==1 (
    ::copying a directory c from d, /s:  boş olanlar hariç, /e:boş olanlar dahil
    xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
    )
ELSE IF %F%==0 IF %C%==0 (
    ::moving a directory
    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
    rd /s /q "%sourceMoveDirectory%"
    )

mavhc's user avatar

asked Jun 18, 2012 at 11:21

eponymous's user avatar

4

Your syntax is incorrect. You can’t use ELSE IF. It appears that you don’t really need it anyway. Simply use multiple IF statements:

IF %F%==1 IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

IF %F%==1 IF %C%==0 (
    ::moving the file c to d
    move "%sourceFile%" "%destinationFile%"
    )

IF %F%==0 IF %C%==1 (
    ::copying a directory c from d, /s:  boş olanlar hariç, /e:boş olanlar dahil
    xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
    )

IF %F%==0 IF %C%==0 (
    ::moving a directory
    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
    rd /s /q "%sourceMoveDirectory%"
    )

Great batch file reference: http://ss64.com/nt/if.html

answered Jun 18, 2012 at 11:29

James Hill's user avatar

James HillJames Hill

60.4k21 gold badges145 silver badges161 bronze badges

8

I think in the question and in some of the answers there is a bit of confusion about the meaning of this pseudocode in DOS: IF A IF B X ELSE Y. It does not mean IF(A and B) THEN X ELSE Y, but in fact means IF A( IF B THEN X ELSE Y). If the test of A fails, then he whole of the inner if-else will be ignored.

As one of the answers mentioned, in this case only one of the tests can succeed so the ‘else’ is not needed, but of course that only works in this example, it isn’t a general solution for doing if-else.

There are lots of ways around this. Here is a few ideas, all are quite ugly but hey, this is (or at least was) DOS!

@echo off

set one=1
set two=2

REM Example 1

IF %one%_%two%==1_1 (
   echo Example 1 fails
) ELSE IF %one%_%two%==1_2 (
   echo Example 1 works correctly
) ELSE (
    echo Example 1 fails
)

REM Example 2

set test1result=0
set test2result=0

if %one%==1 if %two%==1 set test1result=1
if %one%==1 if %two%==2 set test2result=1

IF %test1result%==1 (
   echo Example 2 fails
) ELSE IF %test2result%==1 (
   echo Example 2 works correctly
) ELSE (
    echo Example 2 fails
)

REM Example 3

if %one%==1 if %two%==1 (
   echo Example 3 fails
   goto :endoftests
)
if %one%==1 if %two%==2 (
   echo Example 3 works correctly
   goto :endoftests
)
echo Example 3 fails
)
:endoftests

wjandrea's user avatar

wjandrea

28.6k9 gold badges62 silver badges82 bronze badges

answered Apr 26, 2013 at 20:47

gtpunch's user avatar

gtpunchgtpunch

6415 silver badges3 bronze badges

1

AFAIK you can’t do an if else in batch like you can in other languages, it has to be nested if‘s.

Using nested if‘s your batch would look like

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    ) ELSE (
        IF %F%==1 IF %C%==0(
        ::moving the file c to d
        move "%sourceFile%" "%destinationFile%"
        ) ELSE (
            IF %F%==0 IF %C%==1(
            ::copying a directory c from d, /s:  boş olanlar hariç, /e:boş olanlar dahil
            xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
            ) ELSE (
                IF %F%==0 IF %C%==0(
                ::moving a directory
                xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
                rd /s /q "%sourceMoveDirectory%"
                )
            )
        )
    )

or as James suggested, chain your if‘s, however I think the proper syntax is

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

answered Jun 18, 2012 at 11:29

Bali C's user avatar

Bali CBali C

30.6k35 gold badges123 silver badges152 bronze badges

5

here is how I handled if else if situation

if %env%==dev ( 
    echo "dev env selected selected"
) else (
    if %env%==prod (
        echo "prod env selected"
    )
)

Note it is not the same as if-elseif block as the other programming languages like C++ or Java but it will do what you need to do

answered May 20, 2020 at 12:27

Amado Saladino's user avatar

I believe you can use something such as

if ___ (

do this

) else if ___ (

do this

)

Ophir Yoktan's user avatar

Ophir Yoktan

8,1877 gold badges59 silver badges106 bronze badges

answered Sep 29, 2014 at 9:21

user4090570's user avatar

3

A little bit late and perhaps still good for complex if-conditions, because I would like to add a «done» parameter to keep a if-then-else structure:

set done=0
if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
if %done%==0 (echo do something)

answered Oct 2, 2016 at 11:21

Stefane's user avatar

IF...ELSE IF constructs work very well in batch files, in particular when you use only one conditional expression on each IF line:

IF %F%==1 (
    ::copying the file c to d
    copy "%sourceFile%1" "%destinationFile1%"
) ELSE IF %F%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%" )

In your example you use IF...AND...IF type construct, where 2 conditions must be met simultaneously. In this case you can still use IF...ELSE IF construct, but with extra parentheses to avoid uncertainty for the next ELSE condition:

IF %F%==1 (IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile1%" "%destinationFile1%" )
) ELSE IF %F%==1 (IF %C%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%"))

The above construct is equivalent to:

IF %F%==1 (
    IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile1%" "%destinationFile1%"
    ) ELSE IF %C%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%"))

Processing sequence of batch commands depends on CMD.exe parsing order. Just make sure your construct follows that logical order, and as a rule it will work. If your batch script is processed by Cmd.exe without errors, it means this is the correct (i.e. supported by your OS Cmd.exe version) construct, even if someone said otherwise.

Community's user avatar

answered Aug 8, 2016 at 2:36

sambul35's user avatar

sambul35sambul35

1,06814 silver badges22 bronze badges

Here’s my code Example for if..else..if

which do the following

Prompt user for Process Name

If the process name is invalid

Then it’s write to user

Error : The Processor above doesn't seem to be exist 

if the process name is services
Then it’s write to user

Error : You can't kill the Processor above 

if the process name is valid and not services
Then it’s write to user

the process has been killed via taskill

so i called it Process killer.bat
Here’s my Code:

@echo off

:Start
Rem preparing the batch  
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%  

:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid 
Cls 
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist    

) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls 
Color 0c
Title Permission denied 
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above 

) else (
REM if the process name is valid and not services
Cls 
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)

pause>nul



REM If else if Template
REM if thing1 (
REM Command here 2 ! 
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )

answered Feb 28, 2018 at 8:26

Oimar Daif's user avatar

In this tutorial, you will learn about decision making structures that are the batch file if else statements.

if else batch file

Basically programming logic is all about True (1) or False (0). Like any other programming language, batch file if else statements facilitate us to make a decision between true/false or multiple options by imposing a particular condition.

Batch file if else statement

– Syntax

if (condition) dosomething

:: For if..else if
if (condition) (statement1) else (statement2)

So, as the syntax signifies, first a condition is checked and if true, the corresponding statements are executed in the batch file if statement. As for batch file if else, first a condition of if statement is checked and if true, the statement1 is executed else statement2 is executed.

Batch File If Else Flowchart

Here is a flowchart to highlight the concept of if else statement.

batch file if else

Now that we have known about how batch file if else works, let’s go through some examples.

Batch File If Else Example: Checking Integer Variables And String Variables

To know in depth and details about batch file variables, go through this article.

SET /A a=2
SET /A b=3
SET name1=Aston
SET name2=Martin

:: Using if statement
IF %a%==2 echo The value of a is 2
IF %name2%==Martin echo Hi this is Martin

:: Using if else statements
IF %a%==%b% (echo Numbers are equal) ELSE (echo Numbers are different)
IF %name1%==%name2% (echo Name is Same) ELSE (echo Name is different)
PAUSE

Now this will generate following output.

batch file if else output

Batch File If Else Example To Check If Variable Is Defined Or Not

@echo OFF

::If var is not defined SET var = hello
IF "%var%"=="" (SET var=Hello)

:: This can be done in this way as well
IF NOT DEFINED var (SET var=Hello)

Either way, it will set var to 'Hello' as it is not defined previously.

Batch File If Else Example To Check If A File Or Folder Exists

EXIST command is used to check if a file exists or not. Read this article to know details of EXIST and all the other batch file commands.

@echo OFF

::EXIST command is used to check for existence
IF EXIST D:\abc.txt ECHO abc.txt found
IF EXIST D:\xyz.txt (ECHO xyz.txt found) ELSE (ECHO xyz.txt not found)

PAUSE

Now, let’s assume we have "abc.txt" in D drive and "xyz.txt" doesn’t exist in D: , then it will generate following output.

batch file if exist

So, that’s all about batch file if else statements. We hope you didn’t have a hard time learning about it and hopefully, by this time, you will know how to use if else in batch file scripting.



If-else statements are pretty straightforward, but you might not know how to use them in Windows batch files. Here’s all you need to use them.

Batch files are one of Windows’ hidden secrets for productivity. With just a bit of work, you can automate monotonous tasks and never worry about them again. Power users should learn all about batch scripting sooner rather than later.

One thing you’ll need to know when writing your first batch files is the if-else statement. As you might know if you have any programming experience, the if-else statement is a way to control scripting logic. It allows you to specify a condition that branches into different blocks of code.

If the condition is true, the code in the if block executes. Otherwise, the code in the else block runs instead. Here’s a basic example to help you visualize it:

 if (cash > 10) output "You have enough money!";
else output "You don't have enough money.";

The following syntax is how to use the if-else statement in batch files:

 if %x%==15 (echo "The value of x is 15") else (echo "Unknown value") 

This example works when you are expecting a certain input and anything else can output a standard message. But there’s another scenario that has a different solution.

In most programming languages, you can use a a modified form of the if-else statement. Adding else if in the second statement allows you to execute a different block of code if the initial statement is false but a second condition returns true, like in this modified example:

 if (cash > 20) output "You have lots of money!";
else if (cash > 10) output "You have enough money!";
else output "You don't have enough money.";

However, you can’t use else if in batch scripting. Instead, simply add a series of if statements:

 if %x%==5 if %y%==5 (echo "Both x and y equal 5.")
if %x%==10 if %y%==10 (echo "Both x and y equal 10.") else (echo "Invalid input.")

Interested in more? Check out why PowerShell might be even better than batch scripting.

Have you ever used if-else statements in batch scripting? What do you use batch files to accomplish? Share with us in the comments!

Image Credit: Aaban via Shutterstock.com

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

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

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

  • Windows azure pack что это
  • Windows bat file open file
  • Windows admin center скачать торрент
  • Windows alarms windows 10 что это
  • Windows basic theme windows 10