Paolo.Bolzoni
Paolo.Bolzoni

Reputation: 2556

General solution for a program's exit status with set -e

I am programming in Bash now and I use set -e because to continue the script when a program has failed is hardly the wanted behavior.

When it is I use ||true if I do not need the exit code.

If I need the exit code I wrap the execution like this:

set +e
call_I_need_the_exit_code with few arguments
RV="$?"
set -e
# use "$RV" somewhat

However, it is verbose and I seldom switch set +e and set -e introducing annoying bugs.

Is there a way to make a function that executes the command and setup a known variable to the exit code?

Something like this (pseudocode):

safe_call( call_I_need_the_exit_code(with, few, arguments) )
# use "$RV" somewhat

where safe_call basically does the previous block of code. It would make my code easier to write and read...

Upvotes: 8

Views: 145

Answers (1)

tripleee
tripleee

Reputation: 189347

The reason || true works is that conditionals are safe under set -e. This can be extended easily to your scenario.

command && rv=0 || rv=$?

As an aside, you should avoid uppercase for your private variables.

Upvotes: 5

Related Questions