Some of the answers given here are incorrect because they lead to a test against a variable that will not be determined if do_work succeeds.
We must also consider a successful case, so the answer is:
set -eu do_work && status=0 || status=1
The poster question is a bit ambiguous because it says in the text βI mistakenly want a return code,β but then the code implies βI always want a return codeβ
To illustrate, here is the problematic code:
set -e do_work() { return 0 } status=123 do_work || status=$? echo $status
In this code, the value is printed as 123, not 0, as we might hope.
Mark
source share