Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

exit-code

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...

like image 686
Paolo.Bolzoni Avatar asked Jul 06 '18 07:07

Paolo.Bolzoni


1 Answers

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.

like image 103
tripleee Avatar answered Sep 27 '22 19:09

tripleee