views:

3028

answers:

3

How would you implement logical operators in DOS Batch files?

+4  A: 

Although the DOS If statement doesn't support logical operators (such as "AND" and "OR") you can "cascade" your Ifs to create an implicit conjunction.

http://www.rs-freeware.org/adb/adbdos.htm

If Exist File1.Dat If Exist File2.Dat Goto FILE12_EXIST_LABEL

The idea is that file 1 and 2 both exist then jump to the named label (FILE12_EXIST_LABEL).

See also: IF /?

Dave Jarvis
Yes. Here is the documentation on what IF does support: http://technet.microsoft.com/en-us/library/bb490920.aspx
jeffamaphone
+4  A: 

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
)
paxdiablo
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
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
A: 

An alternative is to look for a unix shell which does give you logical operators and a whole lot more. You can get a native win32 implementation of a Bourne shell here if you don't want to go the cygwin route. A native bash can be found here. I'm quite certain you could easily google other good alternatives such as zsh or tcsh.

K

Kev
If you're going to go through the effort of using a different shell, at least go with PowerShell: http://microsoft.com/powershell
Eclipse