Yes, there is such same thing called Call Stack in Bash as you see in C, Python, etc. The information is stored in BASH_SOURCE, BASH_LINENO, and FUNCNAME. They all are arrays with same length/depth. The last item represents main script, the first item is the current function (or main script) of where these arrays are accessed.
Here is some working code, the first file test.sh:
#!/bin/bash # Copyright 2012 Yu-Jie Lin # MIT License # Log Call Stack LSLOGSTACK () { local i=0 local FRAMES=${#BASH_LINENO[]} # FRAMES-2 skips main, the last one in arrays for ((i=FRAMES-2; i>=0; i--)); do echo ' File' \"${BASH_SOURCE[i+1]}\", line ${BASH_LINENO[i]}, in ${FUNCNAME[i+1]} # Grab the source code of the line sed -n "${BASH_LINENO[i]}{s/^/ /;p}" "${BASH_SOURCE[i+1]}" done } source src.sh # LINE 18 func2 () { func3 foo bar } # LINE 22 func1 () { func2 a b c } # LINE 26 func1 1 2 3
This is extracted from something I am currently working on, which will be released under the MIT License, so this small code is with same license. The second file src.sh is for being sourced:
func3 () { LSLOGSTACK }
And the output:
$ ./test.sh File "./test.sh", line 27, in main func1 1 2 3 File "./test.sh", line 24, in func1 func2 a b c File "./test.sh", line 20, in func2 func3 foo bar File "src.sh", line 2, in func3 LSLOGSTACK
It may look vaguely familiar to you if you are also a Python coder, the code mimics the output of Traceback module.
The explanation of those three arrays can be found in man bash. I am also planning to print out BASH_ARGV for each frame, but that will be in that library I am coding.
0 comments:
Post a Comment