在Bash 脚本中,使用if [[ $0 == ${BASH_SOURCE[0]} ]]; then的模式功能上与 Python 中的if __name__ == "__main__":语句相似。这个 Shell 脚本的构造在如下两种情境中判断当前脚本是被直接执行还是被 source: 脚本被直接执行(如./script.sh):此时$0与${BASH_SOURCE[0]}相同,都是脚本的名称,因此...
source是bash的内建命令,把文件读取到当前bash中执行,相当于在当前bash手动输入命令,所以$0是bash. 示例代码如下: a.sh echo"in a.sh. \$0 is: $0" b.sh echo"in b.sh. \$0 is: $0". ./a.sh 运行如下: lxw ~$echo$0bashlxw~$ source a.shina.sh. $0is:bashlxw~$ source b.shinb.sh. $0...
Hi in some of the scripts you are still using dirname $0 to get the script folder. This doesn't work all the time. And should be replaced by either BASH_SOURCE[0] or another solution.Owner Damangir commented Jan 16, 2014 Thanks for reporting. Replaced with (cd(dirname "${BASH_...
${BASH_SOURCE[0]}(or, more simply,$BASH_SOURCE[1]) contains the (potentially relative) path of the containing script inallinvocation scenarios, notably also when the script issourced, which is not true for$0. Furthermore, asCharles Duffypoints out,$0can be set to anarbitraryvalue by the...