I’m trying to create an err
function to be used by bash-scripts. The function is supposed to emulate BSD’s err(3)
— printing the specified message and exiting with the code specified as the first argument:
function err {
# set +u
# The first argument must be an integer exit-code:
if ! declare -i code=${1:?err called with no arguments}
then
code=70 # Use EX_SOFTWARE by default
fi
shift
if [ -t 2 ]
then
# Use color -- red -- printing final errors to a terminal:
printf "e[1;31m%se[1;0mn" "$*" >&2
else
echo "$*" >&2
fi
set -x
exit $code
}
This works as expected, when invoked correctly, such as err 1 Date is empty
. But, when invoked with no arguments or when the first argument is not numeric, an error in the declare
-line is reported, but not handled: depending on whether -u
is set, the script either dies right there on the declare
-line, or code
is initialized with 0, and the script exits with that — instead of 70.
What am I doing wrong?