Reputation: 24160
I am using set -e
to abort on errors.
But for particular one function I want to ignore error and on error I want return code of the function.
Example:
do_work || true
if [ $? -ne 0 ]
then
echo "Error"
fi
But it is not work return code is always true due || true
How to get return code on do_work on error ?
Upvotes: 12
Views: 9228
Reputation: 111
Several of the answers given here are not correct, because they result in a test against a variable that will be un-defined if do_work
succeeds.
We need to cover the successful case as well, so the answer is:
set -eu
do_work && status=0 || status=1
The poster's question is a little ambiguous because it says in the text "on error I want return code" but then the code implies "I always want the return code"
To illustrate, here is problematic code:
set -e
do_work() {
return 0
}
status=123
do_work || status=$?
echo $status
In this code the value printed is 123, and not 0 as we might hope for.
Upvotes: 11
Reputation: 58948
do_work || status=$?
if [ $status -ne 0 ]
then
echo "Oh no - Fail whale $status has arrived"
fi
Upvotes: 1
Reputation: 44424
One way is to use a pipe, -e
only looks at the right-most result of a pipe:
set -e
do_work | true
retn=${PIPESTATUS[0]}
if (( $retn != 0 ))
then
echo "Error $retn"
fi
echo Ending
I wrote a simple do_work
which just did exit 42
and got the following output:
Error 42
Ending
The PIPESTATUS
array is maintained by Bash, with each element giving the return code of each part of the pipeline. We need to capture it at once (hence $retn
) since it is overwritten at each command.
Of course this might be problematic if your do_work
includes a pipe itself.
Upvotes: 4
Reputation: 5072
You could use a subshell shortcut:
( set +e; do_work )
if [ $? -ne 0 ]
then
echo "Error"
fi
Hope this helps =)
Upvotes: 8