Bash ignore error and get return code

I use set -e to abort errors.

But for a specific function, I want to ignore the error, and if I want to, I want to get the function return code.

Example:

 do_work || true if [ $? -ne 0 ] then echo "Error" fi 

But the return code is not always true due to || true

How to get return code on do_work on error?

+7
source share
5 answers
 do_work || { status=$? echo "Error" } 
+6
source

You can use the subtitle shortcut:

 ( set +e; do_work ) if [ $? -ne 0 ] then echo "Error" fi 

Hope this helps =)

+4
source

One way is to use the pipe, -e only looks at the rightmost pipe result:

 set -e do_work | true retn=${PIPESTATUS[0]} if (( $retn != 0 )) then echo "Error $retn" fi echo Ending 

I wrote a simple do_work that just did exit 42 and got the following output:

 Error 42 Ending 

The PIPESTATUS array PIPESTATUS supported by Bash, with each element giving a return code for each part of the pipeline. We need to fix it right away (hence $retn ), since it is overwritten with every command.

Of course, this can be problematic if your do_work includes the channel itself.

+4
source

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.

+4
source
 do_work || status=$? if [ $status -ne 0 ] then echo "Oh no - Fail whale $status has arrived" fi 
+1
source

All Articles