Windows batch files: multiple if conditions

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 15:26:43

问题


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]

回答1:


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.




回答2:


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)



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/6060046/windows-batch-files-multiple-if-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!