How to exit a batch program after an error?

I have a batch file that does a few things. If one of them fails, I want to exit the entire program. For instance:

@echo off
type foo.txt 2>> error.txt >> success.txt
mkdir bob

If the foo.txt file is not found, I want the stderr message to be added to the error.txt file, otherwise the contents of the foo.txt file are added to the success.txt file. Basically, if a type command returns stderr, then I want the batch file to exit rather than create a new directory. How can you find out if an error has occurred and decide whether to continue the next command or not?

+5
source share
1 answer

use ERRORLEVELto check the exit code of the previous command:

 if ERRORLEVEL 1 exit /b

EDIT: : " , EQUAL GREATER, X" ( if /?). ,

 if exist foo.txt echo yada yada

, :

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

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

All Articles