windows 在 IF 语句中使用 OR WinXP Batch Script

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7273433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:58:47  来源:igfitidea点击:

Using an OR in an IF statement WinXP Batch Script

windowsbatch-fileif-statementcmdconditional

提问by Mechaflash

Is there a way to pass an OR through an IF statement?

有没有办法通过 IF 语句传递 OR?

Such as:

如:

SET var=two
IF "%var%"=="one" OR "two" OR "three" ECHO The number is between zero and four.

回答by Joey

No.

不。

if "%var%"=="one" goto foo
if "%var%"=="two" goto foo
if "%var%"=="three" goto foo
goto afterfoo
:foo
echo The number is between one and three (technically incorrect, since it includes the end points and thus is not between).
:afterfoo

If you need a more structured approach:

如果您需要更结构化的方法:

if "%var%"=="one" set OneToThree=1
if "%var%"=="two" set OneToThree=1
if "%var%"=="three" set OneToThree=1
if defined OneToThree (
    echo Foo
) else (
    rem something
)

回答by Arun

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:

在游戏中有点晚了,但仍然假设这是否可以帮助任何人在这个问题上绊倒。我这样做的方法是使用管道回声组合到 findstr,这样:

(echo ":one: :two: :three:" | findstr /i ":%var%:" 1>nul 2>nul) && (
    echo The number is between zero and four
)

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 var variable.

由于 findstr 是一个外部命令,我建议不要在可能经历 1000 次迭代的循环中使用它。如果情况并非如此,这应该可以解决您尝试执行的操作,而不是使用多个 if。此外,“:”的选择也没有什么特别之处,只需使用一个分隔符,它不太可能成为 var 变量值的一部分。

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.

感谢其他人指向另一个似乎有类似问题的链接,我也会在那里发布此回复,以防万一有人偶然发现该问题并且没有完全到达这里。

回答by myusrn

See duplicate question IF... OR IF... in a windows batch filewhere following solution proposed by @Apostolos

看到重复的问题IF... OR IF... in a windows batch filewhere 以下解决方案由@Apostolos 提出

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

e.g.

例如

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

I found to be the most straight forward and simple to use case in my batch scripts.

我发现这是我的批处理脚本中最直接和最简单的用例。