1

I'm somewhat of a Bash newbie (in terms of scripting) and want to know the preferred method of error checking. I'm writing a build script that goes through a number of commands and I want the script to stop if any of the commands exit with anything other than 0. Other than checking the response code after each command, is there a "universal" way of exiting the script if anything returns a non-0? Thanks!

darksideofthesun
  • 601
  • 2
  • 9
  • 19
  • Have a look at this one: http://stackoverflow.com/questions/64786/error-handling-in-bash It discusses various possibilities. – lxg Sep 08 '14 at 21:25

1 Answers1

0

use set -e at the beginning of your script.

It will stop the script from running after a command fails and the error code will be forwarded.

From bash documentation:

  -e      Exit immediately if a pipeline (which may consist  of  a
          single  simple command),  a subshell command enclosed in
          parentheses, or one of the commands executed as part  of
          a  command  list  enclosed  by braces (see SHELL GRAMMAR
          above) exits with a non-zero status.  The shell does not
          exit  if  the  command that fails is part of the command
          list immediately following a  while  or  until  keyword,
          part  of  the  test  following  the  if or elif reserved
          words, part of any command executed in a && or  ││  list
          except  the  command  following  the final && or ││, any
          command in a pipeline but the last, or if the  command’s
          return  value  is being inverted with !.  A trap on ERR,
          if set, is executed before the shell exits.  This option
          applies to the shell environment and each subshell envi-
          ronment separately (see  COMMAND  EXECUTION  ENVIRONMENT
          above), and may cause subshells to exit before executing
          all the commands in the subshell.
ArnonZ
  • 3,822
  • 4
  • 32
  • 42
  • The examples shown in this faq show when `set -e` doesn't exit **on purpose**. It's a good reference and these examples should be taken into consideration when writing bash. Anyhow, I strongly support the following statement: "Every script you write should include set -e at the top." check [this](http://www.davidpashley.com/articles/writing-robust-shell-scripts/) link regarding robust bash scripts for more info. – ArnonZ Sep 08 '14 at 21:31
  • I don't disagree, but I wanted to make the OP and possible other readers aware of the fact that `set -e` can have undesired side effects. – lxg Sep 08 '14 at 21:34