0

Why does a logical bash operator after a function call ignore errors in the function?

#!/bin/bash
set -e
echo "start script"
bad_func (){ echo 'start bad_func' ; false ; echo 'done bad_func' ; }
bad_func || { echo bad func failed ; exit 1 ; }
echo "finish script"

OUTPUT:

start script
start bad_func
done bad_func
finish script

(and script exits 0)

This works as expected if the logical operator is removed:

#!/bin/bash
set -e
echo "start script"
bad_func (){ echo 'start bad_func' ; false ; echo 'done bad_func' ; }
bad_func
echo "finish script"

OUTPUT:

start script
start bad_func

(and script exits 1)

Please supply reference to documentation when answering.

Tested with bash 5.1.12

usr30742
  • 1
  • 1
  • 1
    [BashFAQ #105](https://mywiki.wooledge.org/BashFAQ/105) covers this. (The gist of that FAQ entry is "don't ever use `set -e`", and that's advice I stand behind). – Charles Duffy Jan 10 '22 at 19:44
  • Duplicate of https://stackoverflow.com/questions/60035954/bash-set-e-does-not-work-when-used-in-if-expression ? Except the quote in the answer is missing the continuation `... part of any command executed in a && or || ...` – KamilCuk Jan 10 '22 at 19:47
  • (https://www.in-ulm.de/~mascheck/various/set-e/ is also worth reading to get an idea of just how varied different "POSIX-compliant" shells' implementations of `set -e` are; not only does it have surprising effects, but they differ shell-to-shell, so keeping an accurate mental model that's accurate across shells is effectively impossile). – Charles Duffy Jan 10 '22 at 19:47

0 Answers0