2 # Copyright 2018 Ian Kelling
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 # Commentary: Bash stack trace and error handling functions. This file
18 # is meant to be sourced. It loads some functions which you may want to
19 # call manually (see the comments at the start of each one), and then
20 # runs err-catch. See the README file for a slightly longer explanation.
23 # help: turn off exit and stack trace on error. undoes err-catch
24 set +E
+o pipefail
; trap ERR
28 # help: print stack trace
30 # Note: It does not show function args unless you first run:
32 # err-catch runs this for you.
34 local -i argc_index
=0 frame i start
=${1:-1} max_indent
=8 indent
37 if [[ $
(shopt -p extdebug
) == *-s* ]]; then
40 for ((frame
=0; frame
< ${#FUNCNAME[@]}-1; frame
++)); do
41 argc
=${BASH_ARGC[frame]}
43 ((frame
< start
)) && continue
44 if (( ${#BASH_SOURCE[@]} > 1 )); then
45 source="${BASH_SOURCE[frame+1]}:${BASH_LINENO[frame]}:"
47 indent
=$
((frame-start
+1))
48 indent
=$
((indent
< max_indent ? indent
: max_indent
))
49 printf "%${indent}s↳%sin \`%s" '' "$source" "${FUNCNAME[frame]}"
51 for ((i
=argc_index-1
; i
>= argc_index-argc
; i--
)); do
52 printf " %s" "${BASH_ARGV[i]}"
60 # help: on errors: print stack trace and exit
62 # You can set "${_errcatch_cleanup[@]}" to a command and it will run before exiting.
63 # This function depends on err-bash-trace.
65 set -E; shopt -s extdebug
70 echo "${BASH_SOURCE[1]}:${BASH_LINENO[0]}:in \`$BASH_COMMAND' returned $err"
71 # err trap does not work within an error trap, the following line:
72 err-bash-trace
2; set -e
73 "${_errcatch_cleanup[@]:-:}" # note :-: is to be compatible with set -u
74 echo "$0: exiting with code $err"
82 # usage: err-exit [EXIT_CODE] [MESSAGE]
83 # help: exit and print stack trace.
85 # Use this instead of the exit command to be more informative. default
86 # EXIT_CODE is 1. If only one of EXIT_CODE and MESSAGE is given,
87 # we consider it to be an exit code if it is a number.
88 # This function depends on err-bash-trace.
93 if [[ ${1/[^0-9]/} == "$1" ]]; then
99 printf '%s\n' "$0: $1"
102 echo "${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
104 echo "$0: exiting with code $code"