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
end

The code looks like this:

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

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: