有没有一种方法可以通过IF语句传递OR?
例如:
例如:
SET var=two
IF "%var%"=="one" OR "two" OR "three" ECHO The number is between zero and four.
SET var=two
IF "%var%"=="one" OR "two" OR "three" ECHO The number is between zero and four.
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
)
请参阅重复问题在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
(echo ":one: :two: :three:" | findstr /i ":%var%:" 1>nul 2>nul) && (
echo The number is between zero and four
)
由于findstr是外部命令,我建议不要在可能需要进行数千次迭代的循环内使用它。如果不是这种情况,使用多个if语句来解决问题可能是一个更好的选择。另外,在选择“:”作为分隔符时并没有什么特殊之处,只要选择一个不太可能成为var变量值的一部分的分隔符即可。
感谢其他人提供了指向另一个类似问题的链接,我将在那里发布这个回答,以防有人偶然看到那个问题但没有找到这里。