& 在两个命令之间只会导致两个命令的执行独立于第一个命令的结果。 & 的右侧命令在& 左侧的命令完成后执行,独立于前一个命令的成功或错误,即独立于前一个命令的退出/返回值。
&& 导致有条件地执行第二个命令。仅当第一个命令成功时才执行第二个命令,这意味着以返回码 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 表示之前的命令 not 以退出代码 greater 0 终止。由于命令 dir 和 md 永远不会以负值退出,只有 0 或更大(几乎所有命令和控制台应用程序)并且值 0 是成功的退出代码,这是测试dir 和md 成功执行的正确方法。
关于 errorlevel 的其他有用的 Stack Overflow 主题:
必须注意将无条件运算符& 与&& 和|| 等条件运算符混合使用,因为执行顺序不一定是命令行上命令的顺序。
例子:
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 在第二个 DIR 之后失败时,才需要在执行 ECHO 时使用 ( 和 ) 与结果无关第二个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 或在批处理文件中不使用这两个命令运行批处理文件的区别.