batch-filecmdlogical-operatorswindows-console

Logical operators ("and", "or") in DOS batch


How would you implement logical operators in DOS Batch files?


Solution

  • You can do and with nested conditions:

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

    You can also do this in a short form:

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

    You can do or with a separate variable:

    set res=F
    if %hour% leq 6 set res=T
    if %hour% geq 22 set res=T
    if "%res%"=="T" (
        set state=asleep
    )
    

    Note that this answer is tailored toward cmd batch language, the one found in Windows. You mention "DOS batch" but, based on several points, I think the former choice is a safe bet(1).

    If you really meant the original MS-DOS batch language, you should keep in mind that the if statement was a lot simpler, and you may need to use chunks of if ... goto for control flow, rather than (for example) parentheses or else.


    (1) Supported by the following points: