If-else condition in batch file

做~自己de王妃 提交于 2020-01-06 16:32:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!