如何在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语句不支持逻辑运算符AND和OR。 级联IF语句构成隐式连词:
IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL
如果存在File1.Dat和File2.Dat,则跳转到标签FILE12_EXIST_LABEL。
参见:IF /?
下面的例子展示了如何创建AND语句(用于为命令设置变量或包含参数)。
启动记事本并关闭CMD窗口:
start notepad.exe & exit
如果变量'a' = blah,则设置变量x、y和z的值。
IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)
希望有帮助!
对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
许多人似乎忽略了OR最明显的解决方案,即使用标签。
if "%a%" == "ONE" goto do_thing
if "%a%" == "TWO" (
:do_thing
echo a is equal to ONE or TWO
)
你可以用嵌套条件做和:
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.
推荐文章
- SQL逻辑运算符优先级:And和Or
- 在批处理文件中处理子字符串的最佳方法是什么?
- 如何添加一个设置路径只执行批处理文件?
- 使用.bat文件检查文件夹是否存在
- BAT文件:打开新的cmd窗口并在其中执行命令
- 顺序运行NPM脚本
- NPM卡住给出相同的错误EISDIR:对目录的非法操作,读取错误(本机)
- 如何使用Windows命令行更改目录
- 如何使用批处理文件写入文本文件?
- Windows批处理文件的隐藏特性
- 在Windows批处理脚本中格式化日期和时间
- 如何在windows中使用命令提示符(cmd)列出文件。我试过在Linux中使用“ls”,但它显示一个错误?
- BAT文件执行后保持CMD打开
- 如何在命令提示符中使用空格?
- 如何从批处理文件运行PowerShell脚本