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 one of your commands fails the script will exit

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

command || exit 1