I have errexit (and pipefail) enabled for my shell script, because that's the behaviour I usually want. However, occasionally I want to capture errors and handle them a specific way.
I know that errexit is disabled for commands that contain boolean operators or are to be used as a condition (if, while etc.)
e.g.
git push && true
echo "Pushed: $?"
will echo "Pushed: 0" on success, or "Pushed: something else" on failure.
However, what if I want a subshell to have errexit enabled, but then I wish to capture the exit code of this subshell?
For example:
#!/usr/bin/env bash
set -o errexit
(
git push
echo "Hai"
) && true
echo "Did it work: $?"
The problem is, bash sees the && boolean operator and disables errexit for the subshell. This means that "Hai" is always echo'd. That's not desirable.
How do enable errexit in this subshell, and capture the status code of the subshell without letting that exit code terminate the outer shell without constantly enabling and disabling errexit all over the place?
Update
I have a strong feeling the solution is to use traps and capture the exit signal. Feel free to provide an answer before I self-answer.