1

Essentially, can you achieve this:

if %num1% == 1 echo hi
if %num1% == 5 echo hi
if %num1% == 9 echo hi

In a simpler way such as:

if %num1% == 1,5,9 echo hi

edit: maybe made my intentions more clear.

  • 1
    Does this answer your question? [Logical operators ("and", "or") in DOS batch](https://stackoverflow.com/questions/2143187/logical-operators-and-or-in-dos-batch) – John Wu Nov 29 '20 at 06:50
  • @JohnWu Not really. Perhaps I miss understood but this seems more like a range between different numbers, like anything between 1-5. I may have been unclear but I want something that would have numbers that don't fit on a range. Like 1, 3, 6, 8. – Victor Chavez Nov 29 '20 at 06:53
  • 2
    Try `for %%a in (1 5 9) do if %num1%==%%a echo hi` (use single percents `%a` if at the cmd prompt instead of a batch file). – dxiv Nov 29 '20 at 07:04
  • @dxiv Yes this works – Victor Chavez Nov 29 '20 at 07:08

4 Answers4

5

Use variable expansion find/replace to test if a value is embedded within a test variable. If the result does not match the original test value, then a relevant value was found.

setlocal enableDelayedExpansion
set "test= 1 5 9 "
if !test: %num% =! neq !test! echo Hi

The leading and trailing spaces in test and also around %num% are critical if you might be dealing with numbers >= 10.

Not relevant to number searches, but this technique is not case sensitive - it cannot differentiate between upper and lower case.

dbenham
  • 127,446
  • 28
  • 251
  • 390
1

@dxiv did the following:

for %%a in (1 5 9) do if %num1%==%%a echo hi

This works well for using if then for specific numbers.

1

You can also test dynamically using substring modification within a macro such as:

@Echo off
Set "list=,1,2,3,5,8,13,21,"
Set "num[1]=1"
Set "num[2]=5"
Set "num[3]=9"

Set "CompVal=For %%n in (1 2)Do If %%n==2 (For %%v in (!cVal!)Do (Set "compare=!Var:,%%~v,=,!" & If not "!compare!" == "!Var!" (Echo/%%~v is in Var)Else (Echo/%%~v not found)))Else Set cVal="
Setlocal EnableDelayedExpansion
rem /* usage examples */
rem /* Search for matching list elements from an array */
 For /F "Tokens=2 Delims==" %%i in ('Set num[')Do %CompVal:Var=list%%%i
rem /* Search a defined list var for specific integers */
 %CompVal:Var=list%13;2;22;305
T3RR0R
  • 2,747
  • 3
  • 10
  • 25
0

Here is another method that inverts the conditions and skips echo hi in case all of them are true:

if not %num1% == 1 if not %num1% == 5 if not %num1% == 9 goto :SKIP
echo hi
:SKIP

The operator == forces string comparison, so avoid it to permit numeric comparisons:

if %num1% neq 1 if %num1% neq 5 if %num1% neq 9 goto :SKIP
echo hi
:SKIP

Another method is to use an interim flag-like variable:

set "SKIP="
if %num1% neq 1 if %num1% neq 5 if %num1% neq 9 set "SKIP=#"
if not defined SKIP echo hi
aschipfl
  • 33,626
  • 12
  • 54
  • 99