日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

bash 获取脚本存放路径_如何获取Bash脚本自己的路径

發布時間:2023/12/20 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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是腳本的路徑。 但是,當腳本是源文件時,例如. 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/bashecho "\$0: $0"echo ${FUNCNAME[0]} in ${BASH_SOURCE[0]}. ./b.sh

b.sh

b.sh

#!/bin/bashecho "\$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 獲取腳本存放路徑

總結

以上是生活随笔為你收集整理的bash 获取脚本存放路径_如何获取Bash脚本自己的路径的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。