如何在出错时退出批处理程序?
我有一个可以做几件事的批处理文件。如果其中之一失败,我想退出整个程序。例如:
@echo off
type foo.txt 2>> error.txt >> success.txt
mkdir bob
如果找不到文件 foo.txt,那么我希望将 stderr 消息附加到 error.txt 文件,否则将 foo.txt 的内容附加到 success.txt。基本上,如果 type 命令返回 stderr,那么我希望批处理文件退出而不是创建新目录。如何判断是否发生错误并决定是否需要继续执行下一个命令?
I've got a batch file that does several things. If one of them fails, I want to exit the whole program. For example:
@echo off
type foo.txt 2>> error.txt >> success.txt
mkdir bob
If the file foo.txt isn't found then I want the stderr message appended to the error.txt file, else the contents of foo.txt is appended to success.txt. Basically, if the type command returns a stderr then I want the batch file to exit and not create a new directory. How can you tell if an error occurred and decide if you need to continue to the next command or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
ERRORLEVEL
检查上一个命令的退出代码:编辑:文档说“如果最后一个命令的退出代码等于或大于X,则条件为真”(您可以使用
if /?
进行检查)。除此之外,您还可以检查文件是否存在,如果条件为真,则执行多个命令:
或
use
ERRORLEVEL
to check the exit code of the previous command:EDIT: documentation says "condition is true if the exit code of the last command is EQUAL or GREATER than X" (you can check this with
if /?
). aside from this, you could also check if the file exists withto execute multple commands if the condition is true:
or