Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a batch program upon error?

Tags:

stderr

dos

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?

like image 894
Notorious2tall Avatar asked Jul 21 '10 20:07

Notorious2tall


People also ask

How do I stop a batch program?

Ctrl+C. One of the most universal methods of aborting a batch file, command, or another program while it's running is to press and hold Ctrl + C . This keyboard shortcut sends a SIGINT signal, which cancels or terminates the currently-running program and returns you to the command line.

How do you exit a batch file in cmd?

To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.

How do you exit a command in cmd?

To close or exit the Windows command line window, also referred to as command or cmd mode or DOS mode, type exit and press Enter . The exit command can also be placed in a batch file.

How do you exit a loop in cmd?

The only way to stop an infinitely loop in Windows Batch Script is by either pressing Ctrl + C or by closing the program.


1 Answers

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
 )
like image 193
akira Avatar answered Jan 03 '23 06:01

akira