3

How do i make a batch file to stop running other/next commands if first or any other command fails.

call grails clean 
call grails compile 
call grails package
call grails war 

If grails clean fail then grails compile should not run and same with others.

Sidharth
  • 1,402
  • 2
  • 16
  • 37
  • 2
    Is `grails` a batch file or an executable? Please specify in your batch file `grails` with file extension. The command `call` is needed only for batch files, not for console applications. To exit a batch file on previous command exited not successful use `if errorlevel 1 goto :EOF` or `if errorlevel 1 exit /B 1`. Run in a command prompt window `if /?` and `goto /?` for help on those two commands. Run in command prompt window also `exit /?` for help on this command in case of `grails` is a batch file which needs to exit with an exit code greater 0 on error for parent batch file exit. – Mofi Oct 20 '16 at 06:34
  • 1
    Possible duplicate of [How do I make a batch file terminate upon encountering an error?](http://stackoverflow.com/questions/734598/how-do-i-make-a-batch-file-terminate-upon-encountering-an-error) – roelofs Oct 20 '16 at 06:37
  • `grails` is a batch file @Mofi – Sidharth Oct 20 '16 at 06:49
  • 1
    If `grails` sets the [`ErrorLevel`](http://ss64.com/nt/errorlevel.html), an `if not ErrorLevel 1` (meaning `ErrorLevel` < `1`) query could be used; if `grails` sets the exit code, use [`&&` operator](http://ss64.com/nt/syntax-redirection.html) (execute next command in case of zero exit code); `ErrorLevel` and exit code are equal most of the time but are actually different things... – aschipfl Oct 20 '16 at 09:23

1 Answers1

4

The ERRORLEVEL environment variable holds the return value of the last executed command. So you can use:

IF %ERRORLEVEL% NEQ 0 (
  echo "Previous command execution failed."
  exit %ERRORLEVEL%
)

Please see http://steve-jansen.github.io/guides/windows-batch-scripting/part-3-return-codes.html for details.

joce
  • 9,624
  • 19
  • 56
  • 74