Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
GOTO 0 Avatar asked Aug 24 '13 21:08

GOTO 0


People also ask

What is @echo off in batch script?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

What does %% mean in batch script?

%%i is simply the loop variable. This is explained in the documentation for the for command, which you can get by typing for /? at the command prompt.

What is SC in batch script?

Use the SC (service control) command, it gives you a lot more options than just start & stop . DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services.

What is NX in batch?

This means that your PATH is not defined correctly. Any NX command line application should be launched from a NX Command Prompt to ensure that the environment is set up correctly. Use Start, All Programs, Siemens NX##, Tools, Command Prompt to open a NX command prompt.


1 Answers

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 
like image 57
GOTO 0 Avatar answered Sep 21 '22 11:09

GOTO 0