add trap protection, and option to force remplacement

This commit is contained in:
fatalerrors
2026-03-25 15:14:10 +01:00
parent 30387a4f08
commit 5f5f9c0e71

View File

@@ -46,7 +46,7 @@ function backtrace()
"${FUNCNAME[$i]}" "${BASH_SOURCE[$i]}" "${BASH_LINENO[$(( i-1 ))]}"
((i++))
done
unset func i
unset i
printf "==============================\n"
}
@@ -69,30 +69,37 @@ settrace()
#trap -p ERR
local PARSED
PARSED=$(getopt -oh --long help,on,off,status -- "$@")
PARSED=$(getopt -oh --long help,on,off,status,force -- "$@")
if [[ $? -ne 0 ]]; then
disp E "Invalid options, use \"settrace --help\" to display usage."
return 1
fi
eval set -- "$PARSED"
local force=0
while true; do
case $1 in
-h|--help)
printf "Try to activate backtrace display for script debugging.\n\n"
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 "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" ]]; then
disp W "ERR signal trap is already set, replacing previous trap!"
if [[ ${status} == "on" ]] && [[ $force -eq 0 ]]; then
disp E "ERR signal trap is already set. Use --force to replace it."
return 1
fi
trap "error" ERR
shift
;;
--force)
force=1
shift
;;
--off)
if [[ ${status} != "on" ]]; then
disp W "ERR signal trap is already unset!"
@@ -101,7 +108,7 @@ settrace()
shift
;;
--status)
disp "ERR trap signal is ${status}."
disp i "Trap signal is ${status}."
shift
;;
--)
@@ -114,7 +121,7 @@ settrace()
;;
esac
done
unset status
unset status force
}
export -f settrace
# ------------------------------------------------------------------------------