脚本调用堆栈

最后更新于:2022-04-02 03:53:57

[TOC] ## 环境变量 变量LINENO返回它在脚本里面的行号。 ``` #!/bin/bash echo "This is line $LINENO" ``` 输出 ``` $ ./test.sh This is line 3 ``` ## BASH_SOURCE 变量BASH_SOURCE返回一个数组,内容是当前的脚本调用堆栈。 该数组的0号成员是当前执行的脚本,1号成员是调用当前脚本的脚本,
lib1.sh ``` #! /bin/bash source lib2.sh function func1() { func2 } ```

lib2.sh ``` #!/bin/bash function func2() { echo "func2: BASH_SOURCE0 is ${BASH_SOURCE[0]}" echo "func2: BASH_SOURCE1 is ${BASH_SOURCE[1]}" echo "func2: BASH_SOURCE2 is ${BASH_SOURCE[2]}" } ```


main.sh ``` #!/bin/bash source lib1.sh func1 ```

输出 ``` func2: BASH_SOURCE0 is lib2.sh func2: BASH_SOURCE1 is lib1.sh func2: BASH_SOURCE2 is main.sh ```
';