在Python中,常见的习惯用法是编写如下代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
pass
if __name__ == "__main__":
main()
这样做是为了如果导入Python脚本而不是执行它,那么它的主要方法将不会运行。
Bash中有类似的成语吗?
答案 0 :(得分:3)
这是一个特殊的bash
变量,
An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}
它实际上是一个数组变量,它包含源的堆栈跟踪,其中${BASH_SOURCE[0]}
是最新的。
来自this-site的无耻示例,仅用于演示目的,
脚本aaa.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
source bbb.sh
脚本bbb.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
source ccc.sh
脚本ccc.sh
#!/bin/bash
echo "from ${BASH_SOURCE[0]} : BASH_SOURCE = ${BASH_SOURCE[*]}"
for i in ${BASH_SOURCE[@]}; do
readlink -f $i
done
正在运行aaa.sh
,
from aaa.sh : BASH_SOURCE = aaa.sh
from bbb.sh : BASH_SOURCE = bbb.sh aaa.sh
from ccc.sh : BASH_SOURCE = ccc.sh bbb.sh aaa.sh
/tmp/ccc.sh # -> first element showing the latest script sourced
/tmp/bbb.sh
/tmp/aaa.sh
答案 1 :(得分:3)
您可以在脚本顶部使用此代码段来确定脚本是否来自:
#!/bin/bash
if [[ ${BASH_SOURCE[0]} != $0 ]]; then
printf "script '%s' is sourced in\n" "${BASH_SOURCE[0]}"
fi
当脚本来源时,$0
变为-bash
,否则会保留脚本本身的名称。