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