7

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)

2 Answers 2

7

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.

1
  • Ah, well that syntax errors cause malfunction is hardly unexpected, isn't it? ;-)
    – Joey
    Jul 3, 2010 at 8:34
4

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .