How would you implement logical operators in DOS Batch files?
How would you implement logical operators in DOS Batch files?
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=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:
cmd and windows-console tags;cmd and MS-DOS batch languages, and conflating DOC with the cmd terminal window;The 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 File2.Dat exist then jump to the label FILE12_EXIST_LABEL.
See also: IF /?
Only the OR part is tricky, but with a general boolean expression containing NOT OR AND the only nice solution is this:
REM if A == B OR C == C then yes
(call :strequ A B || call :strequ C C) && echo yes
exit /b
:strequ
if "%1" == "%2" exit /b 0
exit /b 1
A lot of people seem to be missing the most obvious solution for OR which is to use a label.
if "%a%" == "ONE" goto do_thing
if "%a%" == "TWO" (
:do_thing
echo a is equal to ONE or TWO
)
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
If you need the else clause then you can use this syntax:
AND:
if %v1% == a (if %v2% == b (echo yes) else echo no) else echo no
OR:
if %v1% == a (echo yes) else (if %v2% == b (echo yes) else echo no)
Slight modification to Andry's answer, reducing duplicate type commands:
set "A=1" & set "B=2" & call :IF_AND
set "A=1" & set "B=3" & call :IF_AND
set "A=2" & set "B=2" & call :IF_AND
set "A=2" & set "B=3" & call :IF_AND
echo.
set "A=1" & set "B=2" & call :IF_OR
set "A=1" & set "B=3" & call :IF_OR
set "A=2" & set "B=2" & call :IF_OR
set "A=2" & set "B=3" & call :IF_OR
goto :eof
:IF_OR
(if /i not %A% EQU 1 (
if /i not %B% EQU 2 (
echo FALSE-
type 2>nul
)
)) && echo TRUE+
goto :eof
:IF_AND
(if /i %A% EQU 1 (
if /i %B% EQU 2 (
echo TRUE+
type 2>nul
)
)) && echo FALSE-
goto :eof