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?
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.
To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.
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.
The only way to stop an infinitely loop in Windows Batch Script is by either pressing Ctrl + C or by closing the program.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With