447

Possible Duplicate:
Automatic exit from bash shell script on error

How can I have bash stop on the first command failure, without putting stuff like this all through my code?

some_prog || exit 1
some_other_prog || exit 1
Community
  • 1
  • 1
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

1 Answers1

791

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Behrang
  • 46,888
  • 25
  • 118
  • 160
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
  • 178
    Be aware of `set -e` gotchas: http://mywiki.wooledge.org/BashFAQ/105 – Kris Jun 09 '15 at 10:57
  • 1
    @Kris Thanks, this bit me on linux mint. it silently exits script with no message. so i've removed set -e usage. – Luke W Jan 10 '17 at 22:38
  • 6
    @LukeW this is normal. However, the exit code will be non-zero, indicating an error. Also any program that fails normally prints an error message by itself, try with just shebang + `set -e` + e.g. `ls nope`. You get one clear error message, and scripts fails early. Excellent software. – vidstige Nov 08 '17 at 10:20
  • 5
    the linked duplicate has a good answer too https://stackoverflow.com/a/2871034/362951 – mit Jan 18 '19 at 18:16
  • How do I set -e only for a portion of the script and then reset? – Scorb Jun 07 '22 at 21:23
  • 2
    @Scorb use `set +e` – Alok Singhal Jun 08 '22 at 14:27