Ubuntu – How to stop the bash script when a condition fails

bashcommand linescripts

Here it shows to use the || and && in a single line to concatenate the execution of commands: How can I check for apt-get errors in a bash script?

I am trying to stop a script execution if a certain condition fails,

e.g.

false || echo "Obvious error because its false on left" && exit

Here it prints Obvious error because its false on the left and exits the console which is what I wanted.

true || echo "This shouldn't print" && exit

Here, there's no echo print but the exit command runs as well, i.e., the console is closed, shouldn't the exit command not run because the echo command on the right was not executed?
Or is by default a statement considered false on the left hand side of an && operator?

Edit:
I should have mentioned it before, my aim was to echo the error and exit if it was not clear.
w.r.t to my specific case of catching errors when grouping conditions using && and ||, @bodhi.zazen answer solves the problem.

@takatakatek answer makes it more clear about the flow control and the bash guide links are excellent

@muru answer has good explanation of why not to use set -e if you want custom error messages to be thrown with alternatives of using perl and trap which I think is a more robust way and see myself using it from my second bash script onwards!

Best Answer

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.

Related Question