Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

(shell-error-handling@turnkeylinux.org)

share|improve this question
add comment

2 Answers

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.

share|improve this answer
    
Ah, well that syntax errors cause malfunction is hardly unexpected, isn't it? ;-) –  Joey Jul 3 '10 at 8:34
add comment

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|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.