How to stop the bash script when a condition fails?

The problem is that || and && only skip one subsequent stanza of a command chain when the condition fails. If you write out a full block structure it makes perfect sense. What you wrote becomes this:

if ! true ; then
   echo "This shouldn't print"
else
   exit
fi

What you want is this:

if ! true ; then
   echo "This shouldn't print"
   exit
fi

When you are using Bash's shortcut conditional operators it is better to avoid mixing them. The logic is much easier to understand while you're writing it, and your readers will appreciate your good style.

  • http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Control_Operators
  • http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3

You probably want (as pointed out by steeldriver)

true || { echo "This shouldn't print" && exit; }

Otherwise your script is reading one conditional at at time

a or b and then exit

I think you want a or (b and exit) ?


You could start the script with:

#!/bin/bash -e

The -e ensures that the script exits the moment something returns false (or any non-zero number). A specific failure can then be avoided with something || true

Alternatively, if you want to postpone error checking until later in the script, you can use set -e:

#!/bin/bash
false  # script continues happily
set -e
false  # script stops