天天看點

[Shell]擷取目前正在執行腳本的絕對路徑

1. pwd指令

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

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

  2. echo `pwd`

  3. xiaosi@Qunar:~/company/sh$ sh pwd.sh

  4. /home/xiaosi/company/sh

  5. xiaosi@Qunar:~/company/sh$ cd ..

  6. xiaosi@Qunar:~/company$ sh sh/pwd.sh

  7. /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的值是檔案的名字

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

  2. echo $0

  3. xiaosi@Qunar:~/company/sh$ sh pwd.sh

  4. pwd.sh

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

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

3. 正解

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

dirname $0,取得目前執行的腳本檔案的父目錄 

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

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