如何在DOS批处理文件中实现逻辑操作符?
当前回答
许多人似乎忽略了OR最明显的解决方案,即使用标签。
if "%a%" == "ONE" goto do_thing
if "%a%" == "TWO" (
:do_thing
echo a is equal to ONE or TWO
)
其他回答
下面的例子展示了如何创建AND语句(用于为命令设置变量或包含参数)。
启动记事本并关闭CMD窗口:
start notepad.exe & exit
如果变量'a' = blah,则设置变量x、y和z的值。
IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)
希望有帮助!
许多人似乎忽略了OR最明显的解决方案,即使用标签。
if "%a%" == "ONE" goto do_thing
if "%a%" == "TWO" (
:do_thing
echo a is equal to ONE or TWO
)
另一种选择是寻找unix shell,它可以提供逻辑操作符和更多的功能。如果您不想走cygwin路线,您可以在这里获得Bourne shell的本地win32实现。本地bash可以在这里找到。我很确定你可以很容易谷歌其他好的替代品,如zsh或tcsh。
K
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
Athul Prakash (age 16 at the time) gave a logical idea for how to implement an OR test by negating the conditions in IF statements and then using the ELSE clause as the location to put the code that requires execution. I thought to myself that there are however two else clauses usually needed since he is suggesting using two IF statements, and so the executed code needs to be written twice. However, if a GOTO is used to skip past the required code, instead of writing ELSE clauses the code for execution only needs to be written once.
下面是一个可测试的例子,我将如何实现Athul Prakash的否定逻辑来创建一个OR。
在我的例子中,如果某人有坦克执照或者正在服兵役,他就可以开坦克。在两个提示中输入true或false,你将能够看到逻辑是否允许你驾驶坦克。
@ECHO OFF
@SET /p tanklicence=tanklicence:
@SET /p militaryservice=militaryservice:
IF /I NOT %tanklicence%==true IF /I NOT %militaryservice%==true GOTO done
ECHO I am driving a tank with tanklicence set to %tanklicence% and militaryservice set to %militaryservice%
:done
PAUSE
推荐文章
- 如何运行一个PowerShell脚本而不显示窗口?
- 为什么这个Windows批处理文件只执行第一行,而在命令shell中执行所有三行?
- 如何将文件内容读入批处理文件中的变量?
- 如何验证批处理文件中是否存在一个文件?
- 如何循环通过文件匹配通配符在批处理文件
- 异步运行Windows批处理文件命令
- 为什么git在Windows下记不住我的密码
- 如何在批处理文件中请求管理员访问
- 从Windows批处理文件设置系统环境变量?
- SQL逻辑运算符优先级:And和Or
- 在批处理文件中处理子字符串的最佳方法是什么?
- 如何添加一个设置路径只执行批处理文件?
- 使用.bat文件检查文件夹是否存在
- BAT文件:打开新的cmd窗口并在其中执行命令
- 顺序运行NPM脚本