Search code examples
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:

    • The presence of the cmd and windows-console tags;
    • Prior experience of some people failing to recognise the very real difference between cmd and MS-DOS batch languages, and conflating DOC with the cmd terminal window;
    • The question using the more generic "DOS" rather than specifically "MS-DOS" (where "DOS" could possibly be any disk operating system;
    • The fact this is Stack Overflow rather than the retro-computing sister site, where a question about MS-DOS would be way more appropriate (I'm often on that site as well, it's nice for those of us who remember and appreciate computer history); and
    • The (eventual) acceptance of the answer by the original asker, indicating that the solution worked.