Bash Error Handling – Prevent Shell from Exiting with set -e

bashcommand-substitutionerror handlingset

I have set -e turned on for my script. The only thing is there is one command here that I don't want causing the script to exit if it fails, but I want everything else to do that. How can I keep set -e on, and not have my script exit when an error code is thrown?

script in question:

native=$(pacman -Qenq -)

If stdin has a non-native package name an error code gets written to stdin.

Best Answer

set -e aka set -o errexit doesn't apply to commands that are parts of conditions like in:

if cmd; do
until cmd; do
while cmd; do
cmd || whatever
cmd && whatever

That also applies to the ERR trap for shells supporting it.

So, an idiomatic way to ignore the failure of a command is with:

cmd || : errors ignored

Or just:

cmd || true
cmd || :

That cancels set -e for that cmd invocation and also sets $? to 0 (to that of :/true when cmd fails)

cmd && true
ret=$?

Also cancels set -e but preserves the exit status of cmd.

Related Question