问题
I need to convert next code (C language) condition to batch file:
if(version == 1 || version == 2)
{
// do something
}
else
{
// do something other
}
So in batch file it will be looks like:
if "%version%"==1 (
// do something
)
if "%version%"==2 (
// do something
)
if not "%version%"==1 (
// do something other
)
if not "%version%"==2 (
// do something other
)
Is there more better way to write it?
回答1:
"There is no logic and/or but you can use the mighty goto.
if "%version%"=="1" goto :TRUE
if "%version%"=="2" goto :TRUE
REM do something else
echo neither 1 or 2 :(
goto :eof
:TRUE
REM do something
echo 1 or 2 :)
回答2:
setlocal EnableDelayedExpansion
set wantedVersions=/1/2/
if "!wantedVersions:/%version%/=!" neq "%wantedVersions%" (
echo Version %version% is 1 or 2, do something
) else (
echo Version %version% is NOT 1 or 2, do something other
)
This expression: "!wantedVersions:/%version%/=!"
means: "In wantedVersion eliminate the string "/%version%/"; this way if version is 1 or 2, that value will be eliminated and the result will be different than the original => version is 1 or 2. The slashes are needed to avoid the false identification of version=12.
Yes, I know this method seems complicated, but it is simpler than the other options. Just try to imagine how the other options should be if you have 3 different values, or 4... Also, this method may be nested inside other IF/FOR commands with no problems.
回答3:
Another way with the same philosophy as @Aacini's answer
@ECHO OFF
set /p $var=version ? :
set "$version=[1] [2]"
echo %$version% | find "[%$var%]" && echo do something || echo do something else
来源:https://stackoverflow.com/questions/24139331/if-else-condition-in-batch-file