如何在bash中找到另一个脚本调用的脚本名称(“sourced”)?

How to find out name of script called (“sourced”) by another script in bash?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
In the bash script how do I know the script file name?
How can you access the base filename of a file you are sourcing in Bash

当使用source从另一个脚本调用bash脚本时,我无法从该脚本中找出被调用脚本的名称。

文件1.SH

1
2
3
#!/bin/bash
echo"from file1: $0"
source file2.sh

文件2.SH

1
2
#!/bin/bash
echo"from file2: $0"

运行file1.sh

1
2
3
$ ./file1.sh
from file1: ./file1.sh  # expected
from file2: ./file1.sh  # was expecting ./file2.sh

问:我怎样才能从file2.sh中取回file2.sh


file2.sh改为:

1
2
#!/bin/bash
echo"from file2: ${BASH_SOURCE[0]}"

注意,BASH_SOURCE是一个数组变量。有关更多信息,请参见bash手册页。


如果您source一个脚本,那么您将强制该脚本在当前进程/shell中运行。这意味着您运行的file1.sh脚本中的变量不会丢失。由于$0设置为file1.sh,它保持不变。

如果你想知道file2的名字,你可以这样做-

文件1.SH

1
2
3
#!/bin/bash
echo"from file1: $0"
./file2.sh

文件2.SH

1
2
#!/bin/bash
echo"from file2: $0"