4

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.

8
  • 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. Commented Sep 20, 2017 at 3:32
  • pacman -Qenq - is run with stdin holding a foreign package native ends up being unset.
    – ZeroPhase
    Commented Sep 20, 2017 at 4:26
  • 1
    No it doesn't, because you set it. Something else is going on. Commented Sep 20, 2017 at 4:27
  • ... and your -x output shows it being set (to an empty string, but set). Commented Sep 20, 2017 at 4:28
  • Alright, it's having set -e turned on for the script.
    – ZeroPhase
    Commented Sep 20, 2017 at 4:37

2 Answers 2

11

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .