[TOC] ## 目录不存在问题 ``` #! /bin/bash dir_name=/path/not/exist cd $dir_name rm * ``` 如果 /path/not/exist,则会删除用户下的文件 修复1: ``` [[ -d $dir_name ]] && cd $dir_name && rm * // or 通过 echo 先打印要删除的东西 [[ -d $dir_name ]] && cd $dir_name && echo rm * ``` ## bash -x script.sh 自己打印命令 ## 环境变量 变量LINENO返回它在脚本里面的行号。 ``` #!/bin/bash echo "This is line $LINENO" ``` 输出 ``` $ ./test.sh This is line 3 ``` ## BASH_SOURCE 变量BASH_SOURCE返回一个数组,内容是当前的脚本调用堆栈。 该数组的0号成员是当前执行的脚本,1号成员是调用当前脚本的脚本, <details> <summary>lib1.sh</summary> ``` #! /bin/bash source lib2.sh function func1() { func2 } ``` </details> <br /> <details> <summary>lib2.sh</summary> ``` #!/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]}" } ``` </details> <br /> </details> <br /> <details> <summary>main.sh</summary> ``` #!/bin/bash source lib1.sh func1 ``` </details> <br /> 输出 ``` func2: BASH_SOURCE0 is lib2.sh func2: BASH_SOURCE1 is lib1.sh func2: BASH_SOURCE2 is main.sh ```