tumchaaditya
tumchaaditya

Reputation: 1297

How can I use multiple conditions in "If" in batch file?

Can I specify multiple conditions with "or"/"and" in batch file if block?

If not that complex, can I at least use something like:

if value1 < value < value2

Basically my purpose is to check whether current system time falls in a certain interval(2.05 AM and 7.55 AM to be precise) and if it does, to execute certain commands.

Upvotes: 13

Views: 92811

Answers (4)

Dissmi
Dissmi

Reputation: 11

Set "IF=Set "or_=" & (If"
Set "OR=set "or_=1" )& (If "
Set "AND= If "
Set "THEN= set "or_=1" ) & If defined or_ "

Echo: Sample 1
%IF% 1 EQU 2 %OR% 6 NEQ 3 %OR% /I "stp" EQU "Stp" %THEN% Echo Pass

Echo: Sample 2
%IF% 1 EQU 2 %OR% 6 EQU 3 %AND% "stp" EQU "Stp" %THEN% (
    Echo Pass
) Else Echo Faill

You may mix it but should keep in mind:

  • IF ~ if (
  • OR ~ ) OR (
  • AND ~ AND (parentless)
  • THEN ~ ) Then

So example 2 will be treated as: If ( ex1 ) or ( ex2 and ex3 ) then

Upvotes: 1

MOBASHIR IMAM
MOBASHIR IMAM

Reputation: 89

You can break your condition into 2 and use if and if for setting 2 conditions

if %value% GTR %value1% (
echo Value is greater that %value1% ) else call :Error
if %value% LSS %value2% (
echo Value is less than %value2% ) else call :Error
::Write your Command if value lie under specified range
exit

:Error
echo Value doesn't lie in the range 
::Write your command for if value doesn't lie in the range
exit

Upvotes: 1

Eitan T
Eitan T

Reputation: 32930

Adding to dbenham's answer, you can emulate both logical operators (AND, OR) using a combination of if and goto statements.

To test condition1 AND codition2:

    if <condition1> if <condition2> goto ResultTrue

:ResultFalse
REM do something for a false result
    goto Done

:ResultTrue
REM do something for a true result

:Done

To test condition1 OR codition2:

    if <condition1> goto ResultTrue
    if <condition2> goto ResultTrue

:ResultFalse
REM do something for a false result
    goto Done

:ResultTrue
REM do something for a true result

:Done

The labels are of course arbitrary, and you can choose their names as long as they are unique.

Upvotes: 34

dbenham
dbenham

Reputation: 130829

There are no logic operators in batch. But AND is easy to mimic with two IF statements

if value1 lss value if value lss value2 REM do something

Batch IF statements don't know how to compare times. Batch IF knows how to compare integers and strings.

One option is to convert the times into minutes or seconds past midnight.

The other option is to format the time with both hours, minutes (and seconds if needed) to be 2 digits wide each (0 prefixed as needed). The hours should be 24 hour format (military time).

Upvotes: 9

Related Questions