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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8911724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:20:51  来源:igfitidea点击:

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

bash

提问by Max

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

可能重复:
在 bash 脚本中,我如何知道脚本文件名?
如何访问您在 Bash 中采购的文件的基本文件名

When using sourceto call a bash script from another, I'm unable to find out from within that script what the name of the called script is.

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

file1.sh

文件1.sh

#!/bin/bash
echo "from file1: 
#!/bin/bash
echo "from file2: 
$ ./file1.sh
from file1: ./file1.sh  # expected
from file2: ./file1.sh  # was expecting ./file2.sh
"
" source file2.sh

file2.sh

文件2.sh

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

Running file1.sh

运行 file1.sh

#!/bin/bash
echo "from file1: 
#!/bin/bash
echo "from file2: ##代码##"
" ./file2.sh

Q: How can I retrieve file2.shfrom file2.sh?

问:我怎样才能检索到file2.shfile2.sh

回答by dogbane

Change file2.shto:

更改file2.sh为:

##代码##

Note that BASH_SOURCEis an array variable. See the Bash man pages for more information.

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

回答by jaypal singh

if you sourcea script then you are forcing the script to run in the current process/shell. This means variables in the script from file1.shyou ran are not lost. Since $0was set to file1.shit remains as is.

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

If you want to get the name of file2then you can do something like this -

如果你想得到名字,file2那么你可以做这样的事情 -

file1.sh

文件1.sh

##代码##

file2.sh

文件2.sh

##代码##