Windows 批处理文件中等效的 Switch 语句 [英] Switch statement equivalent in Windows batch file
问题描述
我想知道是否有一种简单的方法可以根据单个表达式的值在 Windows 批处理文件中分支执行.类似于 C、C++、C#、Java、JavaScript、PHP 和其他实际编程语言中的 switch/case 块.
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 块,其中重复检查相同表达式与不同值的相等性:
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. Is there a better solution?
推荐答案
我最终使用了包含 AjV Jsy 建议的 case 表达式值的标签名称.无论如何,我使用 CALL
而不是 GOTO
跳转到正确的 case 块和 GOTO :EOF
跳转回来.以下示例代码是一个完整的批处理脚本,用于说明该想法.
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
这篇关于Windows 批处理文件中等效的 Switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!