fix debug robustness

This commit is contained in:
fatalerrors
2026-07-09 10:55:20 +02:00
parent 2702682fae
commit b2b25843ff

View File

@@ -37,7 +37,7 @@
# ------------------------------------------------------------------------------
# Display a backtrace
# Usage: backtrace
function backtrace()
backtrace()
{
printf "========= Call stack =========\n"
local i=1 # We begin at 1 to ignore backtrace itself
@@ -52,7 +52,7 @@ function backtrace()
# ------------------------------------------------------------------------------
# Function to be trapped for errors investigation
function error()
error()
{
local errcode=$?
backtrace
@@ -64,10 +64,6 @@ function error()
# Usage: settrace <--on|--off|--status>
settrace()
{
local status="off"
[[ $(trap -p ERR) ]] && status="on"
#trap -p ERR
local PARSED
PARSED=$(getopt -oh --long help,on,off,status,force -- "$@")
# shellcheck disable=SC2181 # getopt return code is checked immediately after
@@ -76,7 +72,10 @@ settrace()
return 1
fi
eval set -- "$PARSED"
local force=0
# First pass: gather the requested action and flags. --on, --off and
# --status are mutually exclusive; --force only modifies --on.
local action="" force=0
while true; do
case $1 in
-h|--help)
@@ -84,34 +83,24 @@ settrace()
printf "Options:\n"
printf "\t--on\t\tActivate backtrace generation\n"
printf "\t--force\t\tForce replacement of existing trap (use with --on)\n"
printf "\t--off\t\tDeactivate backtrace generation\n\n"
printf "\t--off\t\tDeactivate backtrace generation\n"
printf "\t--status\tDisplay whether the ERR trap is set\n\n"
printf "That function active a trap event on error. If the script you want to\n"
printf "debug overload the ERR bash trap, it will not work.\n"
return 0
;;
--on)
if [[ ${status} == "on" ]] && [[ $force -eq 0 ]]; then
disp E "ERR signal trap is already set. Use --force to replace it."
--on|--off|--status)
if [[ -n $action ]]; then
disp E "The --on, --off and --status options are mutually exclusive."
return 1
fi
trap "error" ERR
action="${1#--}"
shift
;;
--force)
force=1
shift
;;
--off)
if [[ ${status} != "on" ]]; then
disp W "ERR signal trap is already unset!"
fi
trap - ERR
shift
;;
--status)
disp I "Trap signal is ${status}."
shift
;;
--)
shift
break
@@ -122,7 +111,33 @@ settrace()
;;
esac
done
unset status force
# Second pass: evaluate the current trap state, then apply the action.
local status="off"
[[ -n $(trap -p ERR) ]] && status="on"
case $action in
on)
if [[ $status == "on" && $force -eq 0 ]]; then
disp E "ERR signal trap is already set. Use --force to replace it."
return 1
fi
set -o errtrace
trap "error" ERR
;;
off)
[[ $status != "on" ]] && disp W "ERR signal trap is already unset!"
trap - ERR
set +o errtrace
;;
status)
disp I "Trap signal on error is ${status}."
;;
"")
disp E "No action specified, use \"settrace --help\" to display usage."
return 1
;;
esac
}
export -f settrace
# ------------------------------------------------------------------------------