如何在DOS批处理文件中实现逻辑操作符?
当前回答
下面的例子展示了如何创建AND语句(用于为命令设置变量或包含参数)。
启动记事本并关闭CMD窗口:
start notepad.exe & exit
如果变量'a' = blah,则设置变量x、y和z的值。
IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)
希望有帮助!
其他回答
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.
对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
另一种选择是寻找unix shell,它可以提供逻辑操作符和更多的功能。如果您不想走cygwin路线,您可以在这里获得Bourne shell的本地win32实现。本地bash可以在这里找到。我很确定你可以很容易谷歌其他好的替代品,如zsh或tcsh。
K
下面的例子展示了如何创建AND语句(用于为命令设置变量或包含参数)。
启动记事本并关闭CMD窗口:
start notepad.exe & exit
如果变量'a' = blah,则设置变量x、y和z的值。
IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)
希望有帮助!
推荐文章
- 如何运行一个PowerShell脚本而不显示窗口?
- 为什么这个Windows批处理文件只执行第一行,而在命令shell中执行所有三行?
- 如何将文件内容读入批处理文件中的变量?
- 如何验证批处理文件中是否存在一个文件?
- 如何循环通过文件匹配通配符在批处理文件
- 异步运行Windows批处理文件命令
- 为什么git在Windows下记不住我的密码
- 如何在批处理文件中请求管理员访问
- 从Windows批处理文件设置系统环境变量?
- SQL逻辑运算符优先级:And和Or
- 在批处理文件中处理子字符串的最佳方法是什么?
- 如何添加一个设置路径只执行批处理文件?
- 使用.bat文件检查文件夹是否存在
- BAT文件:打开新的cmd窗口并在其中执行命令
- 顺序运行NPM脚本