bash 获取脚本存放路径
Bash script may need to get its own path. In normal Bash script, $0
is the path to the script. However, when a script is sourced, such as . a.sh
, a.sh
‘s $0
does not give a.sh
while the caller’s name. How to reliably get a bash script’s own path no matter whether the Bash script is executed or sourced is introduced in this post.
Bash 脚本可能需要获取自己的路径。 在普通的Bash脚本中, $0
是脚本的路径。 但是,当脚本是源文件时,例如. a.sh
. a.sh
, a.sh
的$0
不会在调用者的名字时给出a.sh
这篇文章介绍了如何可靠地获取bash脚本自己的路径,而不管Bash脚本是执行还是源代码。
简短答案∞ (Short answer ∞)
You can use ${BASH_SOURCE[0]}
to get the script’s own path, in sourced or directly executed Bash script.
您可以使用${BASH_SOURCE[0]}
获取源代码或直接执行的Bash脚本中脚本的自身路径。

为什么${BASH_SOURCE[0]}
包含自己的路径∞ (Why ${BASH_SOURCE[0]}
contains the own path ∞)
From bash manual
:
从bash manual
:
BASH_SOURCE
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
一个数组变量,其成员是源文件名,在其中定义了FUNCNAME数组变量中的相应外壳函数名称。 外壳函数$ {FUNCNAME [$ i]}在文件$ {BASH_SOURCE [$ i]}中定义,并从$ {BASH_SOURCE [$ i + 1]}中调用。
What about ${BASH_SOURCE[0]
? This following example shows it well.
${BASH_SOURCE[0]
怎么样? 下面的示例很好地说明了这一点。
We have 2 Bash scripts: a.sh and b.sh which is sourced by a.sh and contains a function.
我们有2个Bash脚本:a.sh和b.sh,它们由a.sh派生并包含一个函数。
a.sh
灰
#!/bin/bash
echo "\$0: $0"
echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}
. ./b.sh
b.sh
b.sh
#!/bin/bash
echo "\$0: $0"
echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}
fun() {
echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}
echo $0
}
fun
What happens if we run a.sh directly by sh a.sh
?
如果我们直接由sh a.sh
运行a.sh会发生什么?
The result is as follows.
结果如下。
$0: a.sh
main in a.sh
$0: a.sh
source in ./b.sh
fun in ./b.sh
a.sh
What about we source a.sh by . a.sh
instead of executing it? It gives
那么我们通过提供a.sh呢. a.sh
. a.sh
而不是执行它? 它给
$0: bash
source in a.sh
$0: bash
source in ./b.sh
fun in ./b.sh
bash
In summary, in sourced or directly executed bash script files, ${BASH_SOURCE[0]
contains the path of the bash source file and ${FUNCNAME[0]
contains “source” or “main”. So, ${BASH_SOURCE[0]}
gives you a reliable variable for the Bash script source file path no matter whether it is used inside of a function and no matter whether the script is directed executed or sourced.
总之,在源或直接执行的bash脚本文件中 , ${BASH_SOURCE[0]
包含bash源文件的路径,而${FUNCNAME[0]
包含“源”或“主”。 因此, ${BASH_SOURCE[0]}
为您提供了一个可靠的Bash脚本源文件路径变量,无论它是在函数内部使用还是脚本是直接执行还是源代码化。
翻译自: https://www.systutorials.com/how-to-get-bash-scripts-own-path/
bash 获取脚本存放路径