如何在DOS批处理文件中实现逻辑操作符?
当前回答
IF语句不支持逻辑运算符AND和OR。 级联IF语句构成隐式连词:
IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL
如果存在File1.Dat和File2.Dat,则跳转到标签FILE12_EXIST_LABEL。
参见:IF /?
其他回答
你可以用嵌套条件做和:
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
如果你需要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)
这就像下面这样简单:
如果和>如果+
if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" *do something*
OR> if // if
set BOTH=0
if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" set BOTH=1
if "%BOTH%"=="0" if "%VAR1%"=="VALUE" *do something*
if "%BOTH%"=="0" if "%VAR2%"=="VALUE" *do something*
我知道还有其他的答案,但我认为我的答案更简单,所以更容易理解。希望这对你有所帮助!;)
许多人似乎忽略了OR最明显的解决方案,即使用标签。
if "%a%" == "ONE" goto do_thing
if "%a%" == "TWO" (
:do_thing
echo a is equal to ONE or TWO
)
推荐文章
- Windows FINDSTR命令的未记录的特性和限制是什么?
- 用Windows任务调度器运行批处理文件
- 如何运行一个PowerShell脚本而不显示窗口?
- 为什么这个Windows批处理文件只执行第一行,而在命令shell中执行所有三行?
- 如何将文件内容读入批处理文件中的变量?
- 如何验证批处理文件中是否存在一个文件?
- 如何循环通过文件匹配通配符在批处理文件
- 异步运行Windows批处理文件命令
- 为什么git在Windows下记不住我的密码
- 如何在批处理文件中请求管理员访问
- 从Windows批处理文件设置系统环境变量?
- SQL逻辑运算符优先级:And和Or
- 在批处理文件中处理子字符串的最佳方法是什么?
- 如何添加一个设置路径只执行批处理文件?
- 使用.bat文件检查文件夹是否存在