开发者

Using an OR in an IF statement WinXP Batch Script [duplicate]

开发者 https://www.devze.com 2023-04-01 02:49 出处:网络
This question already has answers here: IF... OR IF... in a windows batch file (18 answers) Closed 4 years ago.
This question already has answers here: IF... OR IF... in a windows batch file (18 answers) Closed 4 years ago.

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

Such as:

SET var=two
IF "%var%"=="one" OR "two" OR "three" ECHO The number is between z开发者_开发百科ero and four.


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
)


See duplicate question IF... OR IF... in a windows batch file where following solution proposed by @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.


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 ":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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消