在WinXP批处理脚本中使用IF语句中的OR关键字

9
有没有一种方法可以通过IF语句传递OR?
例如:
SET var=two
IF "%var%"=="one" OR "two" OR "three" ECHO The number is between zero and four.
3个回答

16
不。
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 "%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
)

我已经抓狂了=(。我尝试用随机的^&|愚弄它,但没成功lol。 - Anthony Miller
3
你也可以使用这种方法:for %%a in (one two three) do if "%var%"=="%%a" 就跳转到 foo。 - Aacini

1

请参阅重复问题在Windows批处理文件中使用IF... OR IF...,其中@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

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

0
有点晚了,但是假设这可能会帮助到任何遇到这个问题的人。我使用echo和findstr的组合来完成这个操作,具体如下:
(echo ":one: :two: :three:" | findstr /i ":%var%:" 1>nul 2>nul) && (
    echo The number is between zero and four
)

由于findstr是外部命令,我建议不要在可能需要进行数千次迭代的循环内使用它。如果不是这种情况,使用多个if语句来解决问题可能是一个更好的选择。另外,在选择“:”作为分隔符时并没有什么特殊之处,只要选择一个不太可能成为var变量值的一部分的分隔符即可。

感谢其他人提供了指向另一个类似问题的链接,我将在那里发布这个回答,以防有人偶然看到那个问题但没有找到这里。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接