Logical operators (“and”, “or”) in DOS batch

How would you implement logical operators in DOS Batch files?

share|improve this question

7 Answers 7

up vote121down voteaccepted

You can do and with nested conditions:

if %age% geq 2 (
    if %age% leq 12 (
        set class=child
    )
)

or:

if %age% geq 2 if %age% leq 12 set class=child

You can do or with a separate variable:

set res=false
if %hour% leq 6 set res=true
if %hour% geq 22 set res=true
if "%res%"=="true" (
    set state=asleep
)
share|improve this answer
6  
You can also just use set res= or set res=1 and then if defined res which is a little more robust against typos and works even in blocks without explicitly enabling delayed expansion. –  Joey Jan 26 '10 at 23:34
3  
Just to improve your answer a bit... you don't need to explicitly nest the "if" statements... you can just "chain" them, as Dave Jarvis demonstrates below –  JoelFan Jan 28 '10 at 14:44

The MS-DOS IF statement does not support logical operators (AND and OR), cascading IF statements make an implicit conjunction.

IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL

If File1.Dat and File1.Dat exist then jump the label FILE12_EXIST_LABEL.

See also: IF /?

share|improve this answer

De Morgan's laws allow us to convert disjunctions ("OR") into logical equivalents using only conjunctions ("AND") and negations ("NOT"). This means we can chain disjunctions ("OR") on to one line.

This means if name is "Yakko" or "Wakko" or "Dot", then echo "Warner brother or sister".

set warner=true
if not "%name%"=="Yakko" if not "%name%"=="Wakko" if not "%name%"=="Dot" set warner=false
if "%warner%"=="true" echo Warner brother or sister

This is another version of paxdiablo's "OR" example, but the conditions are chained on to one line. (Note that the opposite of leq is gtr, and the opposite of geq is lss.)

set res=true
if %hour% gtr 6 if %hour% lss 22 set res=false
if "%res%"=="true" set state=asleep


+ Recent posts