我尝试了解批处理文件中单个命令行中的多个命令是如何工作的。
dir & md folder1 & rename folder1 mainfolder
和其他具有类似命令的情况,但是 &
替换为 &&
。
dir && md folder1 && rename folder1 mainfolder
1.这两种情况有什么区别?
其他想问的:
一行batch.bat
:
dir & md folder1 & rename folder1 mainfolder
多行batch.bat
:
dir
md folder1
rename folder1 mainfolder
2。这个单行和多行在批处理文件程序上是一样的吗?
还有一件事我想知道:
3.如果我从 main.bat 调用其他批处理文件,它们是否独立运行并同时运行?主批处理文件不等待其他批处理文件中的结束程序?怎么做?
最佳答案
两个命令之间的
&
只会导致独立于第一个命令的结果执行两个命令。 &
的命令右侧在&
的左侧命令完成后执行,与前一个命令的成功或错误无关,即与前一个命令的退出/返回值无关。
&&
导致有条件地执行第二条命令。仅当第一个命令成功时才执行第二个命令,这意味着退出并返回代码 0。
另一种解释参见 Conditional Execution。
dir & md folder1 & rename folder1 mainfolder
因此等于
dir
md folder1
rename folder1 mainfolder
多行替换
dir && md folder1 && rename folder1 mainfolder
会是
dir
if not errorlevel 1 (
md folder1
if not errorlevel 1 (
rename folder1 mainfolder
)
)
if not errorlevel 1
表示之前的命令未以大于0的退出代码终止。由于命令 dir
和 md
永远不会以负值退出,只有 0 或更大(几乎所有命令和控制台应用程序)和值 0 是成功的退出代码,这是测试 dir
和 md
是否成功执行的正确方法。
关于 errorlevel
的其他有用的 Stack Overflow 主题:
- Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
- What are the ERRORLEVEL values set by internal cmd.exe commands?
必须注意将无条件运算符 &
与条件运算符(如 &&
和 ||
混合使用,因为执行顺序不一定是命令行上命令的顺序。
例子:
dir "C:\Users\%UserName%" /AD 2>nul || dir "%UserProfile%" /AD & echo User profile path: "%UserProfile%"
此命令行执行为:
dir "C:\Users\%UserName%" /AD 2>nul
if errorlevel 1 dir "%UserProfile%" /AD
echo User profile path: "%UserProfile%"
ECHO 命令的执行始终独立于第一个 DIR 的执行结果,而第二个 DIR 仅在第一个 DIR 执行时执行 像在 Windows XP 上一样失败,或者用户的配置文件文件夹不在驱动器 C: 上,或者根本不在文件夹 Users
中。
仅当第一个 DIR 在第二个 < strong>DIR 独立于第二个 DIR 的结果。
dir "C:\Users\%UserName%" /AD 2>nul || ( dir "%UserProfile%" /AD & echo User profile path: "%UserProfile%" )
此命令行执行为:
dir "C:\Users\%UserName%" /AD 2>nul
if errorlevel 1 (
dir "%UserProfile%" /AD
echo User profile path: "%UserProfile%"
)
关于第三个问题的答案,请参阅我在 How to call a batch file in the parent folder of current batch file? 上的回答,我在其中解释了使用命令 call
或使用命令 start
或不使用任何命令运行批处理文件的区别批处理文件中的这两个命令。
关于windows - 使用 Windows 批处理文件的单行多命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343351/