简体   繁体   中英

Windows batch files: multiple if conditions

Is there a way to say something like

if %1 == 1 or %1 == 2

in a batch file? Or, even better, if I could specify a set of candidate values like

if %1 in [1, 2, 3, 4, ... 20]

The "and" turns out to be easy -- just not the syntax you expect: These 3 examples illustrate it.

In words: If 1==1 AND 2==2 Then echo "hello"

if 1==1 echo hello
hello

if 1==1 if 2==2 echo hello
hello

if 1==1 if 2==1 echo hello
(nothing was echoed)

One way to implement logical-or is to use multiple conditionals that goto the same label.

if %1 == 1 goto :cond
if %1 == 2 goto :cond
goto :skip
:cond
someCommand
:skip

To test for set membership, you could use a for-loop:

for %%i in (1 2 3 4 ... 20) do if %1 == %%i someCommand

Note that == is the string equality operator. equ is the numeric equality operator.

I know this is old, but I just wanted to let you know, that it indeed is possible, unlike the previous posts said. Basically you are tying two IF commands into one.

Syntax: IF equation (cmd if true)else command if false

Try this for two variables (to perform IF xx AND xx statement)

set varone=1
set vartwo=2

if %varone% equ 1 (if %vartwo% equ 2 (echo TRUE)else echo FALSE)else echo FALSE

with one Variable (to perform OR statement- note you can use more than one variable as well)

if %a% equ 1 (echo pass)else if %a equ 2 (echo pass)else echo false

You can substitute Echo pass/fail with your command

A bit late in the game, but nevertheless assuming if this might help anyone stumbling upon the question. The way I do this is using a combination of echo piped to findstr, this way:

(echo ":1: :2:" | findstr /i ":%1:" 1>nul 2>nul) && (
    echo Input is either 1 or 2
)

Since findstr is an external command, I recommend not using this inside a loop which may go through 1000's of iterations. If that is not the case, this should solve what you are attempting to do instead of using multiple ifs. Also, there is nothing special in the choice of ":", just use a delimiter which is unlikely to be part of the value in the %1.

Thanks to the rest of folks on pointing to another link which appears to have similar question, I will post this response there as well, just in case someone stumbles upon that question and doesn't quite reach here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM