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.

  • 1
    I'm not clear on what the issue you're having is. Empty strings are not unset and the code you have should work fine. – Michael Homer Sep 20 '17 at 3:32
  • pacman -Qenq - is run with stdin holding a foreign package native ends up being unset. – ZeroPhase Sep 20 '17 at 4:26
  • 1
    No it doesn't, because you set it. Something else is going on. – Michael Homer Sep 20 '17 at 4:27
  • ... and your -x output shows it being set (to an empty string, but set). – Michael Homer Sep 20 '17 at 4:28
  • Alright, it's having set -e turned on for the script. – ZeroPhase Sep 20 '17 at 4:37

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

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

| improve this answer | |
  • So what's the difference between the value of $? between cmd || true and cmd || :? – ZeroPhase Sep 20 '17 at 18:32
  • @ZeroPhase, like I said, after cmd || :, $? is 0. After cmd && :, $? is the exit status of cmd. – Stéphane Chazelas Sep 20 '17 at 19:00
> var=
> : ${var:=foo}
> echo "$var"
| improve this answer | |
  • 1
    A tiny bit of explanation would be nice. For example, not everybody knows the : command. – Philippos Sep 20 '17 at 8:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.