0

What's the "right" way to access the exit code of an unsuccessful command?

I ask because I just learned the hard way that the behavior is extremely unintuitive:

If you do

if ! false; then
    echo $?
fi

then it prints 0, whereas if you do

if false; then
    :
else
    echo $?
fi

it prints 1, despite the fact that the two seem logically equivalent.

The second one is obviously a workaround, but is there a more proper way to do this?

Note that I obviously don't want a command with collateral damage here.
For example, merely doing

false
if [ 0 -ne $? ]; then
    echo $?
fi

would have entirely different behavior when set -e is in effect.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • @Cyrus: That doesn't always work (e.g. if `set -e` is in effect). – user541686 Oct 18 '19 at 20:09
  • @anubhava: See my previous comment. – user541686 Oct 18 '19 at 20:12
  • 1
    This might help: `! false; echo $?; false; echo $?` – Cyrus Oct 18 '19 at 20:13
  • @Mehrdad: That should be part of your question not in comments – anubhava Oct 18 '19 at 20:14
  • [Bash get exit status of command when 'set -e' is active?](https://stackoverflow.com/questions/18621990/bash-get-exit-status-of-command-when-set-e-is-active) – KamilCuk Oct 18 '19 at 20:17
  • @Mehrdad, what's unintuitive or surprising about it? `!` has its own exit status; if `true` has an exit status of 0 (truthy!), `! true` has an exit status that's falsey. – Charles Duffy Oct 18 '19 at 20:21
  • @anubhava: Added, but I'd have thought it'd go without saying that I don't want extra behavior that I didn't ask for... can you reopen now? – user541686 Oct 18 '19 at 20:22
  • 1
    And yeah, [`set -e` is an entirely awful idea and should never be used by anyone](http://mywiki.wooledge.org/BashFAQ/105#Exercises). – Charles Duffy Oct 18 '19 at 20:22
  • 1
    If you don't want extra behavior, **don't use `set -e`**. It's a huge collection of hacks and workarounds, and is moreover [different between shells](https://www.in-ulm.de/~mascheck/various/set-e/) and releases of the same shell. – Charles Duffy Oct 18 '19 at 20:23
  • @CharlesDuffy: I'm **well aware of the numerous pitfalls**, but using `&&` has its own pitfalls, and in any case, even I can't always dictate to the other authors of a script whether `set -e` is in effect or not. I need a command that works whether it's in effect or not, regardless of whether I enjoy it. – user541686 Oct 18 '19 at 20:24
  • @KamilCuk: Ah, I guess I need an extra variable then. Thanks! – user541686 Oct 18 '19 at 20:27
  • What exactly are the pitfalls of `foo_rc=0; foo || foo_rc=$?`? – Charles Duffy Oct 18 '19 at 20:32

0 Answers0