Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
tumchaaditya Avatar asked Jun 03 '12 05:06

tumchaaditya


People also ask

How to check multiple conditions in if statement in batch file?

Another option is to use a temporary variable: set "OR=" & ((if <condition1> set "OR=1") & if <condition2> set "OR=1") & if defined OR (echo TRUE) else (echo FALSE) .

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.

Does batch have else if?

However, you can't use else if in batch scripting. Instead, simply add a series of if statements: if %x%==5 if %y%==5 (echo "Both x and y equal 5.")

How do I exit a batch script?

EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.


1 Answers

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.

like image 158
Eitan T Avatar answered Oct 24 '22 21:10

Eitan T