溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Shell如何獲取當(dāng)前正在執(zhí)行腳本的絕對(duì)路徑

發(fā)布時(shí)間:2021-09-10 13:24:46 來源:億速云 閱讀:128 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Shell如何獲取當(dāng)前正在執(zhí)行腳本的絕對(duì)路徑,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

1. pwd命令

?我們看看使用pwd命令能否獲取當(dāng)前正在執(zhí)行腳本的絕對(duì)路徑。該命令的作用是“print name of current/working directory”,真實(shí)含義是當(dāng)前工作目錄,并不是正在執(zhí)行腳本的目錄。

xiaosi@Qunar:~/company/sh$ cat pwd.sh
echo `pwd`
xiaosi@Qunar:~/company/sh$ sh pwd.sh
/home/xiaosi/company/sh
xiaosi@Qunar:~/company/sh$ cd ..
xiaosi@Qunar:~/company$ sh sh/pwd.sh 
/home/xiaosi/company

pwd.sh腳本中只有一句:echo `pwd`。通過在不同路徑下運(yùn)行腳本,sh pwd.sh得到/home/xiaosi/company/sh,然而sh sh/pwd.sh 得到/home/xiaosi/company,所以說pwd命令并不能得到正在執(zhí)行腳本的目錄。

2. $0

$0是Bash環(huán)境下的特殊變量,其真實(shí)含義是:Expands to the name of the shell or shell script. This is set at shell initialization.  If bash is invoked with a file of commands, $0 is set to the name of that file. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero。

$0值與調(diào)用的方式有關(guān):

(1)使用一個(gè)文件調(diào)用bash,那$0的值是文件的名字

xiaosi@Qunar:~/company/sh$ cat pwd.sh 
echo $0
xiaosi@Qunar:~/company/sh$ sh pwd.sh 
pwd.sh

(2)使用-c選項(xiàng)啟動(dòng)bash,真正執(zhí)行的命令會(huì)從一個(gè)字符串中讀取,字符串后面如果還有別的參數(shù)的話,使用從$0開始的特殊變量引用(跟路徑無關(guān)了)

(3)除此以外,$0會(huì)被設(shè)置成調(diào)用bash的那個(gè)文件的名字(沒說是絕對(duì)路徑)

3. 正解

basepath=$(cd `dirname $0`; pwd)

dirname $0,取得當(dāng)前執(zhí)行的腳本文件的父目錄

cd `dirname $0`,進(jìn)入這個(gè)目錄(切換當(dāng)前工作目錄)

pwd,顯示當(dāng)前工作目錄(cd執(zhí)行后的)

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Shell如何獲取當(dāng)前正在執(zhí)行腳本的絕對(duì)路徑”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI