0

I have this batch script that has numerous "if statements". Here are a couple lines of what I have:

if %c%==PC exit
if %c%==pc exit
if %c%==CMD exit
if %c%==cmd exit
if %c%==MENU exit
if %c%==menu exit
if %c%==KILL exit
if %c%==kill exit

There are many more possibilities and really could use some simplifying if it is possible. So is there a way I can simplify this? Perhaps something like, if the variable c is equal to any of these exit. Or even make the if statements case insenstitive Is this possible? Really, any way to simplify this would be awesome and could greatly reduce the size of my batch script.

A couple side notes

  • This code already works and does not need to be edited with the exception of condensing it.

  • I know there is a similar question found here, but I do not know how to apply it to my problem.

Christian Sirolli
  • 246
  • 1
  • 6
  • 18

3 Answers3

6

This is the shortest method:

rem Next line is necessary to nest the value of one variable inside another one
setlocal EnableDelayedExpansion

rem Initialize the list of values enclosed by slash
set "values=/PC/CMD/MENU/KILL/"



if /I "!values:/%c%/=!" neq "%values%" exit
  • The initialization of values variable just needs to made it once, at beginning
  • The !values:/%c%/=! part first replaces the %c% variable; then try to remove such a value enclosed by slashes from !values! variable using Delayed Expansion.
  • If the result is different than the original %values% variable, it means that /%c%/ string appears inside !values!. In this case, execute exit.
  • The /I switch in if command checks for both uppercase and lowercase (and any other letters combination) in %c%.

This method also allows to insert an else part in the if command in the simplest way, because there is just one if.

EDIT: As user LotPings indicated, it is not necessary to include the /I switch in this case because in the %var:old=new% replacement, the old string replacement from %var% value is case insensitive.

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • 4
    The `/i` switch isn't necessary here. The string replacement is case insensitive and the remaining part of value will have the same casing as the complete value. +1 for the solution. –  Mar 11 '17 at 15:37
2

From the HELP for the IF command. The /I switch, if specified, says to do case insensitive string compares. The /I switch can also be used on the string1==string2 form of IF.

if /I %c%==PC exit
if /I %c%==CMD exit
if /I %c%==MENU exit
if /I %c%==KILL exit
Squashman
  • 13,649
  • 5
  • 27
  • 36
1

You can use an array:

set arr=PC pc CMD cmd MENU menu KILL kill
for %%a in (%arr%) do (
if %c%==%%a exit
)

For multiple values, replace the if line with:

if %c%=="PC" if %c%=="pc"

It will only run the next line if all if's are true.

Bali C
  • 30,582
  • 35
  • 123
  • 152