Batchography: How to do a Switch/case in Batch files

You have found this blog post because you are wondering if there is a way to express a “switch/case” logic in Batch files.

The short answer is NO, not exactly. However, there are ways to achieve the same in Batch files.

In the Batchography book, I explain in details the “switch/case” construct, but in this blog post I will illustrate this mechanism briefly. For more advanced Batch scripting topics, please grab a copy of the Batchography book.

batchography-good-res

Get the book from Amazon:

  • Paperback editionbtn-buy-on-amazon
  • E-book editionbtn-buy-on-amazon

flower separator

There is no built-in “switch/case” syntax in the Batch files scripting language, however we can achieve that with environment variables and the GOTO or the CALL syntax.

Consider the following C code and see how to express something similar in the Batch files language:

switch (n)
{
  default:
    printf("Something else\n");
    break;
  case 1:
    printf("One\n");
    break;
  case 2:
    printf("Two\n");
    break;
  case 3:
    printf("Three\n");
    break;
}   
printf("After Switch/case");

In the Batch files scripting language, we can use the GOTO keyword to jump to a dynamically generated label name:

@echo off

echo Switch/case in Batch script

set /P N=Enter switch case number: 

:switch-case-example

  :: Call and mask out invalid call targets
  goto :switch-case-N-%N% 2>nul || (
    :: Default case
    echo Something else
  )
  goto :switch-case-end
  
  :switch-case-N-1
    echo One
    goto :switch-case-end     

  :switch-case-N-2
    echo Two
    goto :switch-case-end

  :switch-case-N-3
    echo Three
    goto :switch-case-end

:switch-case-end
   echo After Switch/case

Please refer to the Batchography book for a more detailed explanation on the switch/case topic and other Batch scripting topics.

flower separatorYou might also like:

Leave a Reply