I'm working on a bash script and as I've been going I've learned about traps, signals, function return codes and other such features I've not previously used.
I may be thinking about things incorrectly - I'm looking for some advice.
I am setting the following options:
set -o errexit
set -o nounset
set -o noclobber
I've got the following exit and err traps in my bash script:
# Error handler. This function is called anytime an ERR signal is received.
# This function should never be explictly called.
function _trap_error () {
if [ ! -v _VERBOSE ]; then
echo "An error has occurred. Exiting."
else
_name="$0" # name of the script
_lastline="$1" # argument 1: last line of error occurence
_lasterr="$2" # argument 2: error code of last command
echo "${_name}: line ${_lastline}: exit status of last command: ${_lasterr}"
exit 1
fi
}
trap '_trap_error ${LINENO} ${$?}' ERR
# Exit handler. This function is called anytime an EXIT signal is received.
# This function should never be explicitly called.
function _trap_exit () {
[ -v _POPD ] && popd &> /dev/null
}
trap _trap_exit EXIT
They work much as I'd expect. Rather than inserting error checking into all my functions, I'm attempting to leverage the traps to handle this for me, for example when checking for the existence of a file. If the specified module can't be loaded, I'd like to catch it as an error, display an error message, and exit.
function _module_path () {
echo "mod.d/$2s/$1/__init__.sh"
}
function _module_exists () {
[ -f $(_module_path $1 $2) ] && return 0 || return 1
}
function _module_push () {
_module_exists $1 $2 && _MODULES+=$( _module_path $1 $2 ) || msg "Module $1 does not exist."
}
However, setting the return code to 0 in conjunction with errexit triggers an EXIT signal, which is caught by my exit trap instead. I started trying to figure out if I can manually emit an ERR signal instead, but haven't found an answer and started to wonder if I'm going about this correctly.