switch语句相当于Windows中的批处理文件 [英] switch statement equivalent in Windows batch file
问题描述
我不知道是否有在Windows批处理文件取决于一个单一的前pression的值分支执行一个简单的方法。一个类似于开关/ case块中的C,C ++,C#,Java和Javascript中,PHP和其他真正的编程语言。
I wonder if there is a simple way to branch execution in a Windows batch file depending on the value of one single expression. Something akin to switch/case blocks in C, C++, C#, Java, Javascript, PHP and other real programming languages.
我的唯一的解决方法是一个普通的if / else块,其中相同的前pression反复检查针对不同的值相等:
My only workaround is a plain if/else block where the same expression is repeatedly checked for equality against different values:
IF "%ID%"=="0" (
REM do something
) ELSE IF "%ID%"=="1" (
REM do something else
) ELSE IF "%ID%"=="2" (
REM do another thing
) ELSE (
REM default case...
)
于是哑巴。任何更好的解决方案?
So dumb. Any better solution?
推荐答案
有关在这个问题依然有人打,我最终使用含有的情况下前pressions值由AjV JSY的建议标签名称。总之,我使用呼叫
而不是 GOTO
跳转到正确的情况下块和 GOTO: EOF
跳回。下面的示例code是一个完整的批处理脚本说明想法。
For anybody still hitting upon this question, I ended up using label names containing the values for the case expressions as suggested by AjV Jsy. Anyway, I use CALL
instead of GOTO
to jump into the correct case block and GOTO :EOF
to jump back. The following sample code is a complete batch script illustrating the idea.
@ECHO OFF
SET /P COLOR="Choose a background color (type red, blue or black): "
2>NUL CALL :CASE_%COLOR% # jump to :CASE_red, :CASE_blue, etc.
IF ERRORLEVEL 1 CALL :DEFAULT_CASE # if label doesn't exist
ECHO Done.
EXIT /B
:CASE_red
COLOR CF
GOTO END_CASE
:CASE_blue
COLOR 9F
GOTO END_CASE
:CASE_black
COLOR 0F
GOTO END_CASE
:DEFAULT_CASE
ECHO Unknown color "%COLOR%"
GOTO END_CASE
:END_CASE
VER > NUL # reset ERRORLEVEL
GOTO :EOF # return from CALL
这篇关于switch语句相当于Windows中的批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!