[windows] IF... OR IF... in a windows batch file

Is there a way to write an IF OR IF conditional statement in a windows batch-file?

For example:

IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE

This question is related to windows batch-file if-statement cmd conditional

The answer is

While dbenham's answer is pretty good, relying on IF DEFINED can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.

While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF with IF /? reveals that,

The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.

In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR check to me, both in regards to underlying logic and readability. For example:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.

If you wanted to have it all on one line, written-wise, you could just chain them together with && like:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

If %x%==1 (
If %y%==1 (
:: both are equal to 1.

That's for checking if multiple variables equal value. Here's for either variable.

If %x%==1 (
:: true
If %x%==0 (
If %y%==1 (
:: true
If %x%==0 (
If %y%==0 (
:: False

I just thought of that off the top if my head. I could compact it more.

A simple "FOR" can be used in a single line to use an "or" condition:

FOR %%a in (item1 item2 ...) DO IF {condition_involving_%%a} {execute_command}  

Applied to your case:

FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE

Suppress executing twice

A comment pointed out that {execute_command} may be encountered twice. To avoid this, you can use a goto after the first encounter.

FOR %%a in (1 2) DO IF %var%==%%a (
    goto :continue

If you think there's a possibility that {execute_command} might be executed twice and you don't want that, you can just add && goto :eof:

FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE && goto :eof

Much simpler, and still on a single line.

I don't think so. Just use two IFs and GOTO the same label:

IF cond1 GOTO foundit
IF cond2 GOTO foundit

ECHO Didn't found it
GOTO end

ECHO Found it!


The goal can be achieved by using IFs indirectly.

Below is an example of a complex expression that can be written quite concisely and logically in a CMD batch, without incoherent labels and GOTOs.

Code blocks between () brackets are handled by CMD as a (pathetic) kind of subshell. Whatever exit code comes out of a block will be used to determine the true/false value the block plays in a larger boolean expression. Arbitrarily large boolean expressions can be built with these code blocks.

Simple example

Each block is resolved to true (i.e. ERRORLEVEL = 0 after the last statement in the block has executed) / false, until the value of the whole expression has been determined or control jumps out (e.g. via GOTO):

 ((DIR c:\xsgdde /w) || (DIR c:\ /w)) && (ECHO -=BINGO=-)

Complex example

This solves the problem raised initially. Multiple statements are possible in each block but in the || || || expression it's preferable to be concise so that it's as readable as possible. ^ is an escape char in CMD batches and when placed at the end of a line it will escape the EOL and instruct CMD to continue reading the current batch of statements on the next line.


    (CALL :ProcedureType1 a b) ^
        || (CALL :ProcedureType2 sgd) ^
            || (CALL :ProcedureType1 c c)
) ^
    && (
        ECHO -=BINGO=-
        GOTO :EOF
ECHO -=no bingo for you=-

    IF "%~1" == "%~2" (EXIT /B 0) ELSE (EXIT /B 1)
GOTO :EOF (this line is decorative as it's never reached)

    ECHO :ax:xa:xx:aa:|FINDSTR /I /L /C:":%~1:">nul

I realize this question is old, but I wanted to post an alternate solution in case anyone else (like myself) found this thread while having the same question. I was able to work around the lack of an OR operator by echoing the variable and using findstr to validate.

for /f %%v in ('echo %var% ^| findstr /x /c:"1" /c:"2"') do (
    if %errorlevel% equ 0 echo true

It's possible to use a function, which evaluates the OR logic and returns a single value.

@echo off
set var1=3
set var2=5
call :logic_or orResult "'%var1%'=='4'" "'%var2%'=='5'"
if %orResult%==1 ( 
    echo At least one expression is true
) ELSE echo All expressions are false
exit /b

:logic_or <resultVar> expression1 [[expr2] ... expr-n] 
set "logic_or.result=0"
set "logic_or.resultVar=%~1"

if "%~2"=="" goto :logic_or_end 
if %~2 set "logic_or.result=1"
goto :logic_or_loop 

  set "%logic_or.resultVar%=%logic_or.result%"
  exit /b

Never got exist to work.

I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.

Never got batch files to work above Windows XP

Thanks for this post, it helped me a lot.

Dunno if it can help but I had the issue and thanks to you I found what I think is another way to solve it based on this boolean equivalence:

"A or B" is the same as "not(not A and not B)"


IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE


IF not [%var%] == [1] IF not [%var%] == [2] ECHO FALSE

Even if this question is a little older:

If you want to use if cond1 or cond 2 - you should not use complicated loops or stuff like that.

Simple provide both ifs after each other combined with goto - that's an implicit or.

//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit

//thats our else.
GOTO end

  echo "doing it"


Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.

A much faster alternative I usually use is as follows, as I can "or" an arbitrary number of conditions that can fit in variable space

  Echo off
  Set "_Match= 1 2 3 "

Set /a "var=3"

Echo:%_Match%|Find " %var% ">nul || (
  REM Code for a false condition goes here
) && (
  REM code for a true condition goes here.

There is no IF <arg> OR or ELIF or ELSE IF in Batch, however...

Try nesting the other IF's inside the ELSE of the previous IF.

IF <arg> (
) ELSE (
    IF <arg> (
    ) ELSE (
        IF <arg> (
        ) ELSE (

Realizing this is a bit of an old question, the responses helped me come up with a solution to testing command line arguments to a batch file; so I wanted to post my solution as well in case anyone else was looking for a similar solution.

First thing that I should point out is that I was having trouble getting IF ... ELSE statements to work inside of a FOR ... DO clause. Turns out (thanks to dbenham for inadvertently pointing this out in his examples) the ELSE statement cannot be on a separate line from the closing parens.

So instead of this:

FOR ... DO (
    IF ... (
    ELSE (

Which is my preference for readability and aesthetic reasons, you have to do this:

FOR ... DO (
    IF ... (
    ) ELSE (

Now the ELSE statement doesn't return as an unrecognized command.

Finally, here's what I was attempting to do - I wanted to be able to pass several arguments to a batch file in any order, ignoring case, and reporting/failing on undefined arguments passed in. So here's my solution...

SET ARGS=(arg1 Arg1 ARG1 arg2 Arg2 ARG2 arg3 Arg3 ARG3)

FOR %%A IN (%*) DO (
    FOR %%B in %ARGS% DO (
        IF [%%A] == [%%B] SET TRUE=1
        SET %%A=TRUE
        ) ELSE (
        SET ARG=%%A


ECHO "%ARG%" is not an acceptable argument.


Note, this will only report on the first failed argument. So if the user passes in more than one unacceptable argument, they will only be told about the first until it's corrected, then the second, etc.

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?

Examples related to conditional

Pandas/Python: Set value of one column based on value in another column Run an Ansible task only when the variable contains a specific string (Excel) Conditional Formatting based on Adjacent Cell Value Laravel Checking If a Record Exists Multiple conditions in if statement shell script The condition has length > 1 and only the first element will be used Creating a new column based on if-elif-else condition How to conditional format based on multiple specific text in Excel Using SUMIFS with multiple AND OR conditions Replacing Numpy elements if condition is met