Switch statement equivalent in Windows batch file
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.
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?
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
This is simpler to read:
IF "%ID%"=="0" REM do something
IF "%ID%"=="1" REM do something else
IF "%ID%"=="2" REM do another thing
IF %ID% GTR 2 REM default case...
Compact form for short commands (no 'echo'):
IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...
After ^
must be an immediate line end, no spaces.
I guess all other options would be more cryptic. For those who like readable and non-cryptic code:
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...
)
It's like an anecdote:
Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...
The IF
ELSE
solution isn't that bad. It's almost as good as python's if
elif
else
. More cryptic 'eggs' can be found here.
I searched switch / case
in batch files today and stumbled upon this. I used this solution and extended it with a goto exit
.
IF "%1"=="red" echo "one selected" & goto exit
IF "%1"=="two" echo "two selected" & goto exit
...
echo "Options: [one | two | ...]
:exit
Which brings in the default state (echo line) and no extra if
's when the choice is found.