Joey Armstrong | 7f382ef | 2023-01-25 12:00:08 -0500 | [diff] [blame] | 1 | #!/bin/bash |
| 2 | ## ----------------------------------------------------------------------- |
| 3 | ## Intent: An example script showing how to source common libraries |
| 4 | ## and produce a stack trace on script error/exit |
| 5 | ## ----------------------------------------------------------------------- |
| 6 | |
| 7 | declare -g fatal=1 # assign to view stack trace |
| 8 | |
| 9 | echo "$0: ENTER" |
| 10 | |
| 11 | echo "$0: Source library shell includes" |
| 12 | |
| 13 | declare -g pgmdir="${0%/*}" # dirname($script) |
| 14 | declare -a common_args=() |
| 15 | common_args+=('--common-args-begin--') |
| 16 | # common_args+=('--traputils') |
| 17 | # common_args+=('--stacktrace') |
| 18 | # common_args+=('--tempdir') |
| 19 | source "${pgmdir}/common.sh" "${common_args[@]}" |
| 20 | |
| 21 | echo "$0: define foo(), bar() & tans()" |
| 22 | |
| 23 | function foo() |
| 24 | { |
| 25 | echo "${FUNCNAME}: hello - stack_frame[1]" |
| 26 | bar |
| 27 | } |
| 28 | |
| 29 | function bar() |
| 30 | { |
| 31 | echo "${FUNCNAME}: hello - stack_frame[2]" |
| 32 | tans |
| 33 | } |
| 34 | |
| 35 | function tans() |
| 36 | { |
| 37 | declare -g fatal |
| 38 | echo "${FUNCNAME}: early exit for stacktrace" |
| 39 | [[ $fatal -eq 1 ]] && exit 1 |
| 40 | return |
| 41 | } |
| 42 | |
| 43 | echo "$0: calling foo() for a stack trace" |
| 44 | foo |
| 45 | |
| 46 | echo "$0: ENTER" |
| 47 | |
| 48 | ## ----------------------------------------------------------------------- |
| 49 | # % ./example.sh |
| 50 | # ./example.sh: ENTER |
| 51 | # ./example.sh: Source library shell includes |
| 52 | # ./example.sh: define foo(), bar() & tans() |
| 53 | # ./example.sh: calling foo() for a stack trace |
| 54 | # foo: hello - stack_frame[1] |
| 55 | # bar: hello - stack_frame[2] |
| 56 | # tans: early exit for stacktrace |
| 57 | # |
| 58 | # OFFENDER: ./example.sh:1 |
| 59 | # ERROR: 'exit 1' exited with status 1 |
| 60 | # Call tree: |
| 61 | # 1: ./example.sh:25 tans(...) |
| 62 | # 2: ./example.sh:19 bar(...) |
| 63 | # 3: ./example.sh:37 foo(...) |
| 64 | # Exiting with status 1 |
| 65 | |
| 66 | # [EOF] |