1

Suppose I want to capture the return code of

(exit 56)

If I use set -e or a zerr handler, I can no longer do:

(exit 56)
ret=$?

If I use (exit 56) || true to avoid set -e, the return code would become zero and I can no longer get it.

So how do I get the return code?

1

1 Answer 1

4

You can use && true instead:

set -o errexit
(exit 50) && true
echo code: $?

Though you could also do:

set -o errexit
if (exit 50) then else
  echo failed with code $?
fi

Or:

set -o errexit
(exit 50) || {
  code=$?
  echo failed with code $code
  # and whatever else you want to do with $code
}

The idea is that errexit is cancelled whenever the failing command is used as a condition, but if you do (exit 50) && true, the exit code after that would always be 0.

(personally, I avoid errexit and prefer doing proper error handling by hand).

2
  • These look like they should work in a standard shell or Bash too, apart from the empty then block, right? That would need to be changed to then true; else (or so) for those other shells. Commented Aug 10, 2021 at 20:52
  • 1
    @ilkkachu, yes though you'd also need to quote the parameter expansions that are in list context there as usual. Commented Aug 10, 2021 at 21:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.