Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch files: multiple if conditions

Is there a way to say something like

 if %1 == 1 or %1 == 2 

in a batch file? Or, even better, if I could specify a set of candidate values like

 if %1 in [1, 2, 3, 4, ... 20] 
like image 889
MxLDevs Avatar asked May 19 '11 14:05

MxLDevs


People also ask

Can you use if statements in batch files?

One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.

Why is %% used in batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What is %% f in batch file?

doc or . txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).


2 Answers

The "and" turns out to be easy -- just not the syntax you expect: These 3 examples illustrate it.

In words: If 1==1 AND 2==2 Then echo "hello"

if 1==1 echo hello hello  if 1==1 if 2==2 echo hello hello  if 1==1 if 2==1 echo hello (nothing was echoed) 
like image 134
Dana Forsberg Avatar answered Nov 04 '22 23:11

Dana Forsberg


One way to implement logical-or is to use multiple conditionals that goto the same label.

if %1 == 1 goto :cond if %1 == 2 goto :cond goto :skip :cond someCommand :skip 

To test for set membership, you could use a for-loop:

for %%i in (1 2 3 4 ... 20) do if %1 == %%i someCommand 

Note that == is the string equality operator. equ is the numeric equality operator.

like image 38
bk1e Avatar answered Nov 05 '22 01:11

bk1e