Shell獲取當前正在執行腳本的絕對路徑

1. pwd命令

我們看看使用pwd命令能否獲取當前正在執行腳本的絕對路徑。該命令的作用是“print name of current/working directory”,真實含義是當前工作目錄,並不是正在執行腳本的目錄。

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`。通過在不同路徑下運行腳本,sh pwd.sh得到/home/xiaosi/company/sh,然而sh sh/pwd.sh 得到/home/xiaosi/company,所以說pwd命令並不能得到正在執行腳本的目錄。

2. $0

$0是Bash環境下的特殊變量,其真實含義是: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值與調用的方式有關:

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

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

(2)使用-c選項啟動bash,真正執行的命令會從一個字符串中讀取,字符串後面如果還有別的參數的話,使用從$0開始的特殊變量引用(跟路徑無關瞭)

(3)除此以外,$0會被設置成調用bash的那個文件的名字(沒說是絕對路徑)

3. 正解

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

dirname $0,取得當前執行的腳本文件的父目錄

cd `dirname $0`,進入這個目錄(切換當前工作目錄)

pwd,顯示當前工作目錄(cd執行後的)

到此這篇關於Shell獲取當前正在執行腳本的絕對路徑的文章就介紹到這瞭,更多相關Shell獲取腳本絕對路徑內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: