-# Commentary: Bash stack trace and error handling functions. This file
-# is meant to be sourced. It loads some functions which you may want to
-# call manually (see the comments at the start of each one), and then
-# runs err-catch. See the README file for a slightly longer explanation.
+#######################################
+# err-catch: Setup trap on ERR to print stack trace and exit (or return
+# if the shell is interactive). This is the most common use case so we
+# run it after defining it, you can call err-allow to undo that.
+#
+# This also sets pipefail because it's a good practice to catch more
+# errors.
+#
+# Note: In interactive shell, stack calling line number is not
+# available, so we print function definition lines.
+#
+# Globals
+#
+# err_catch_ignore Array containing glob patterns to test against
+# filenames to ignore errors from in interactive
+# shell. Initialized to ignore bash-completion
+# scripts on debian based systems.
+#
+# err-cleanup If set, this command will run just before exiting.
+#
+# _err_func_last Used internally in err-bash-trace-interactive
+#
+#######################################
+err-catch() {
+ set -E;
+ if [[ $- == *i* ]]; then
+ if ! test ${err_catch_ignore+defined}; then
+ err_catch_ignore=(
+ '/etc/bash_completion.d/*'
+ '*/bash-completion/*'
+ )
+ fi
+ declare -i _err_func_last=0
+ shopt -s extdebug
+ # shellcheck disable=SC2154
+ trap '_err-bash-trace-interactive $? "$BASH_COMMAND" ${BASH_ARGC[0]} "${BASH_ARGV[@]}" || return $?' ERR
+ else
+ # Man bash on exdebug: "If set at shell invocation, arrange to
+ # execute the debugger". We want to avoid that, but I want this file
+ # to be sourceable from bash startup files. noninteractive ssh and
+ # sources .bashrc on invocation. login_shell sources things on
+ # invocation.
+ #
+ # extdebug allows us to print function arguments in our stack trace.
+ if ! shopt login_shell >/dev/null && [[ ! $SSH_CONNECTION ]]; then
+ shopt -s extdebug
+ fi
+ trap err-exit ERR
+ fi
+ set -o pipefail
+}
+# This is the most common use case so run it now.
+err-catch