- 帖子
- 380
- 积分
- 1159
- 技术
- 28
- 捐助
- 0
- 注册时间
- 2008-8-21
|
[其他] [讨论]对批处理中errorlevel的几点猜测
1. 有些命令执行完毕之后,CMD不会去修改errorlevel的值,比如echo命令。
更多内容请参考:
http://bbs.bathome.net/thread-7479-1-1.html
注:那个帖子的部分结论有待商榷。
2. 有些命令执行完毕之后,且仅当命令执行完毕之后(complete),CMD会去修改errorlevel的值。
2.1 命令执行完毕,而且成功(complete successfully),CMD把errorlevel的值设置为0
c:\Test>time /t
11:01 PM
c:\Test>echo %errorlevel%
0
c:\Test>dir /b a.txt
a.txt
c:\Test>echo %errorlevel%
0 |
2.2 命令执行完毕,但是出错(complete with error),CMD把errorlevel的值设置为非0(大部分时候是1)
c:\Test>time /t
11:02 PM
c:\Test>echo %errorlevel%
0
c:\Test>dir /b a.log
File Not Found
c:\Test>echo %errorlevel%
1 |
3、如果命令在执行过程中被系统发出的中断信号(不同于用户输入的Ctrl+C等组合键)中止(abort),CMD不会去修改errorlevel的值。命令中存在||时,情况有所不同。
3.1
c:\Test>time /t
11:03 PM
c:\Test>echo %errorlevel%
0
c:\Test>attrib +r a.txt
c:\Test>dir >a.txt
Access is denied.
c:\Test>echo %errorlevel%
0 |
注:CMD在解释执行dir >a.txt的过程中,由于重定向的优先级高,于是首先尝试写文件(获取文件a.txt的写权限)。但是因为该文件设置了只读属性,所以操作失败,系统发出中断信号中止掉整条命令。换句话说,dir命令根本没有被执行。
3.2
c:\Test>time /t
11:04 PM
c:\Test>echo %errorlevel%
0
c:\Test>attrib +r a.txt
c:\Test>dir >a.txt || echo bbs.bathome.net
Access is denied.
bbs.bathome.net
c:\Test>echo %errorlevel%
1 |
注:如前文所述,dir >a.txt被中止之后,CMD并未立刻去修改errorlevel的值。它要去判断是否触发||。关于||,微软是这样说的:
Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully.
很显然,||左边的命令没有成功地执行完毕,满足触发||的条件,CMD把errorlevel的值修改为1,然后||认为自己接受到一个非0的返回码,继续执行后面的echo命令。
3.3
c:\Test>time /t
11:05 PM
c:\Test>echo %errorlevel%
0
c:\Test>attrib +r a.txt
c:\Test>dir >a.txt && echo bbs.bathome.net
Access is denied.
c:\Test>echo %errorlevel%
0 |
注:dir >a.txt被中止之后,不满足触发&&的条件,CMD不去修改errorlevel的值,整行命令直接结束。
【扩展阅读】
https://stackoverflow.com/questions/34987885/what-are-the-errorlevel-values-set-by-internal-cmd-exe-commands/34987886#34987886 |
-
1
评分人数
-
-
CrLf:
看来你是对的...感谢分享技术 + 1
|