Apr 132014

While looking for the equivalent of a switch / case statement for Windows batch files, I came across this answer on Stackoverflow.

Basically, what it does is using environment variable substitution for simulating:

case %var% of
  1: rem do something
  2: rem do something else
  3: rem do something completely different

The code looks like this:

call :SomePrefix%var%
goto aftercase
  rem do something
  goto :eof
  rem do something else
  goto :eof
  rem do something completely different
  goto :eof

If “do something” is some complex code that’s pretty nifty and possibly a bit faster than the naive approach:

if "%var%"=="1" rem do something
if "%var%"=="2" rem do something else
if "%var%"=="3" rem do something completely different

But still: The readability suffers quite a lot. And if speed was an issue, why would you use a batch file in the first place? Anyway, I had a use case for it so I used it.

Sorry, the comment form is closed at this time.

%d bloggers like this: