tags:

views:

24

answers:

2

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?

+2  A: 

Typically you decide if a command has failed or not using its exit code, which is stored in ERRORLEVEL; a non-zero exit code means there was some sort of failure. You can use EXIT to stop execution:

IF NOT ERRORLEVEL 0 EXIT
Michael Mrozek
+2  A: 

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

 if ERRORLEVEL 1 exit

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 )

or

 if ERRORLEVEL 1 (
    echo error in previous command
    exit
 )
akira