How to make Batch-file automatically stop on error

14,915

Solution 1

There's really no good way to do what you want given the design of the shell in Windows (inherited from MS-DOS).

Generally speaking, CMD.EXE and COMMAND.COM blithely continue executing batch files even in the face of errors. Checking the errorlevel of programs you call is about all you've got for error handling. Most malformed shell commands will be treated as programs to execute (and, hopefully, whatever program gets executed doesn't do something bad).

Errors in the syntax of constructs like if exists or for will cause the shell to stop executing a script. Consider:

@echo off
if not exits c:\foo.txt echo C:\foo.txt does not exist
echo Continuing on

You'll never see Continuing on because the interpreter will bomb with error c:\foo.txt was unexpected at this time.. Unfortunately, there's no way to trap and handle errors like there is with bash. When you hit an error like this the script stops dead.

In general, error handling in the Windows shell is very non-sophisticated.

Solution 2

An arguable less bad way to stop an batch immediately on error is to use every "instruction" something like:

copy %UNEXISTING% C:\ || ( Echo Error file %UNEXISTING% does not exist & EXIT /B 1)

With || the rest the next command on the same line is executed only if the errorlevel from previous command is different from 0.

Share:
14,915

Related videos on Youtube

jpmartins
Author by

jpmartins

Updated on September 17, 2022

Comments

  • jpmartins
    jpmartins over 1 year

    Do anyone knows if there is a Windows Batch-file equivalent to Unix Stop on Error "#!/bin/sh -e"?

    (http://www.turnkeylinux.org/blog/shell-error-handling)

  • Joey
    Joey almost 14 years
    Ah, well that syntax errors cause malfunction is hardly unexpected, isn't it? ;-)