bash 获取脚本存放路径_如何获取Bash脚本自己的路径
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是腳本的路徑。 但是,當(dāng)腳本是源文件時(shí),例如. a.sh . a.sh , a.sh的$0不會在調(diào)用者的名字時(shí)給出a.sh 這篇文章介紹了如何可靠地獲取bash腳本自己的路徑,而不管Bash腳本是執(zhí)行還是源代碼。
簡短答案∞ (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]}獲取源代碼或直接執(zhí)行的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
一個(gè)數(shù)組變量,其成員是源文件名,在其中定義了FUNCNAME數(shù)組變量中的相應(yīng)外殼函數(shù)名稱。 外殼函數(shù)$ {FUNCNAME [$ i]}在文件$ {BASH_SOURCE [$ i]}中定義,并從$ {BASH_SOURCE [$ i + 1]}中調(diào)用。
What about ${BASH_SOURCE[0]? This following example shows it well.
${BASH_SOURCE[0]怎么樣? 下面的示例很好地說明了這一點(diǎn)。
We have 2 Bash scripts: a.sh and b.sh which is sourced by a.sh and contains a function.
我們有2個(gè)Bash腳本:a.sh和b.sh,它們由a.sh派生并包含一個(gè)函數(shù)。
a.sh
灰
#!/bin/bashecho "\$0: $0"echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}. ./b.shb.sh
b.sh
#!/bin/bashecho "\$0: $0"echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}fun() {echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}echo $0 }funWhat happens if we run a.sh directly by sh a.sh?
如果我們直接由sh a.sh運(yùn)行a.sh會發(fā)生什么?
The result is as follows.
結(jié)果如下。
$0: a.sh main in a.sh $0: a.sh source in ./b.sh fun in ./b.sh a.shWhat about we source a.sh by . a.sh instead of executing it? It gives
那么我們通過提供a.sh呢. a.sh . a.sh而不是執(zhí)行它? 它給
$0: bash source in a.sh $0: bash source in ./b.sh fun in ./b.sh bashIn 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.
總之,在源或直接執(zhí)行的bash腳本文件中 , ${BASH_SOURCE[0]包含bash源文件的路徑,而${FUNCNAME[0]包含“源”或“主”。 因此, ${BASH_SOURCE[0]}為您提供了一個(gè)可靠的Bash腳本源文件路徑變量,無論它是在函數(shù)內(nèi)部使用還是腳本是直接執(zhí)行還是源代碼化。
翻譯自: https://www.systutorials.com/how-to-get-bash-scripts-own-path/
bash 獲取腳本存放路徑
總結(jié)
以上是生活随笔為你收集整理的bash 获取脚本存放路径_如何获取Bash脚本自己的路径的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vs2013 打开失败 未能完成操作,不
- 下一篇: linux构建widi显示服务,如此简单