5

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?

1
  • I added the code IF NOT ERRORLEVEL 0 EXIT /B echo %errorlevel% before the mkdir bob command, but regardless of the value of ERRORLEVEL (i.e. 0 or 1) the directory is still created. So basically, ERRORLEVEL is being set with a different value whether the type command finds the file or not, but the program is not exiting. Thoughts? Commented Jul 21, 2010 at 21:07

1 Answer 1

10

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
 )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.