如何在DOS批处理文件中实现逻辑操作符?


当前回答

试试否定操作数“not”!

好吧,如果你可以使用嵌套的“if”对if语句执行“AND”操作(参考前面的答案),那么你可以对“if not”做同样的事情来执行“or”操作。

如果你还没有完全明白,继续往下读。否则,就不要浪费时间,回到编程中去。

就像嵌套的“if”只有在所有条件为真时才被满足一样,嵌套的“if not”只有在所有条件为假时才被满足。这类似于你想要对'or'操作数做的事情,不是吗?

即使嵌套的“if not”中的任何一个条件为真,整个语句仍然不满足。因此,你可以连续使用否定的“if”,记住条件语句的主体应该是你想要做的,如果所有嵌套的条件都是假的。你真正想要给出的主体应该在else语句下。

如果你还是不明白事情的真相,对不起,我16岁了,我只能解释这么多了。

其他回答

如果你需要else子句,你可以使用下面的语法:

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)

另一种选择是寻找unix shell,它可以提供逻辑操作符和更多的功能。如果您不想走cygwin路线,您可以在这里获得Bourne shell的本地win32实现。本地bash可以在这里找到。我很确定你可以很容易谷歌其他好的替代品,如zsh或tcsh。

K

你可以用嵌套条件做和:

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

or:

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

你可以用一个单独的变量:

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

注意,这个答案是针对cmd批处理语言定制的,在Windows中可以找到。你提到了“DOS批处理”,但是,基于几点,我认为前者的选择是一个安全的赌注(1)。

如果你真的是指原始的MS-DOS批处理语言,你应该记住If语句要简单得多,你可能需要使用If语句的块…Goto表示控制流,而不是(例如)括号或其他。


(1)以下几点支持:

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.

OR有点棘手,但也不过分。这里有一个例子

set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow

对Andry的回答进行了轻微修改,减少了重复的类型命令:

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