开发者

How to exit a batch program upon error?

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 nex开发者_开发技巧t command or not?


use ERRORLEVEL to check the exit code of the previous command:

 if ERRORLEVEL 1 exit /b

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 with

 if exist foo.txt echo yada yada

to execute multple commands if the condition is true:

 if ERRORLEVEL 1 ( echo error in previous command & exit /b )

or

 if ERRORLEVEL 1 (
    echo error in previous command
    exit /b
 )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜