Using an OR in an IF statement WinXP Batch Script

2019-02-13 13:21发布

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 zero and four.

3条回答
再贱就再见
2楼-- · 2019-02-13 13:31

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.

查看更多
混吃等死
3楼-- · 2019-02-13 13:33

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
)
查看更多
来,给爷笑一个
4楼-- · 2019-02-13 13:39

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.

查看更多
登录 后发表回答