Bash – How to exit a shell script if one part of it fails

basherror handlingscripting

How can I write a shell script that exits, if one part of it fails?
For example, if the following code snippet fails, then the script should exit.

n=0
until [ $n -ge 5 ]
do
  gksu *command* && break
  n=$[$n+1]
  sleep 3

Best Answer

One approach would be to add set -e to the beginning of your script. That means (from help set):

  -e  Exit immediately if a command exits with a non-zero status.

So if any of your commands fail, the script will exit.

Alternatively, you can add explicit exit statements at the possible failure points:

command || exit 1
Related Question