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++
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...
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
Hariprasad didupe suggested a solution provided by Batchography, but it could be improved a bit. Unlike with other cases getting into default case will set ERRORLEVEL to 1 and, if that is not desired, you should manually set ERRORLEVEL to 0:
goto :switch-case-N-%N% 2>nul || (
rem Default case
rem Manually set ERRORLEVEL to 0
type nul>nul
echo Something else
)
...
The readability could be improved for the price of a call
overhead:
call:Switch SwitchLabel %N% || (
:SwitchLabel-1
echo One
goto:EOF
:SwitchLabel-2
echo Two
goto:EOF
:SwitchLabel-3
echo Three
goto:EOF
:SwitchLabel-
echo Default case
)
:Switch
goto:%1-%2 2>nul || (
type nul>nul
goto:%1-
)
exit /b
Few things to note:
call
overhead;rem
inside to
avoid parenthesis error;goto:EOF
will exit parent
context). This could be circumvented by replacing goto:%1-
in
subroutine with call:%1-
for the price of additional call
overhead;:-
prefix (which are valid) and
not passing a control variable will lead to default case.