luk*_*uku 21 windows error-handling batch-file io-redirection
假设我们想要使用以下命令在Windows中创建一个空文件:
type nul > C:\does\not\exist\file.txt
Run Code Online (Sandbox Code Playgroud)
目录不存在,所以我们得到错误:
The system cannot find the path specified
Run Code Online (Sandbox Code Playgroud)
如果你打印%errorlevel%输出是:
echo %errorlevel%
0
Run Code Online (Sandbox Code Playgroud)
但命令没有成功!
我注意到,%errorlevel%如果你使用重定向,窗口不会设置最后一个命令.
有没有解决的办法?
dbe*_*ham 29
您可以使用以下内容:
C:\>type nul > C:\does\not\exist\file.txt && echo ok || echo fail
The system cannot find the path specified.
fail
C:\>echo %errorlevel%
1
Run Code Online (Sandbox Code Playgroud)
我总是假设&&和|| 运营商使用ERRORLEVEL,但显然没有.
非常好奇,只有在使用||时才会在重定向错误后设置ERRORLEVEL 运营商.我从来没有猜到过.如果不是你的优秀问题,我也不会费心去测试.
如果您想要做的只是在重定向失败时设置ERRORLEVEL,那么您当然可以这样做:
type nul > C:\does\not\exist\file.txt || rem
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6285 次 |
| 最近记录: |