1. 程式人生 > >bash shell 獲取當前正在執行指令碼的絕對路徑

bash shell 獲取當前正在執行指令碼的絕對路徑

如題,一般我們寫Shell指令碼的時候,都傾向使用絕對路徑,這樣無論指令碼在什麼目錄執行,都應該起到相同的效果,但是有些時候,我們設計一個軟體包中的工具指令碼,可能使用相對路徑更加靈活一點,因為你不知道使用者會在哪個目錄執行你的程式,就有了本文的題目。

  常見的一種誤區,是使用 pwd 命令,該命令的作用是“print name of current/working directory”,這才是此命令的真實含義,當前的工作目錄,這裡沒有任何意思說明,這個目錄就是指令碼存放的目錄。所以,這是不對的。你可以試試 bash shell/a.sh,a.sh 內容是 pwd,你會發現,顯示的是執行命令的路徑 /home/june

,並不是 a.sh 所在路徑:/home/june/shell/a.sh

  另一個誤人子弟的答案,是 $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有可能是好幾種值,跟呼叫的方式有關係:

  • 使用一個檔案呼叫bash,那$0的值,是那個檔案的名字(沒說是絕對路徑噢)

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

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

下面對比下正確答案:

#!/bin/bash
echo '$0: '$0
echo "pwd: "`pwd`
echo "scriptPath1: "$(cd `dirname $0`; pwd)
echo "scriptPath2: "$(dirname $(readlink -f $0))

在此解釋下 scriptPath1 :

  • dirname $0,取得當前執行的指令碼檔案的父目錄

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

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

       由此,我們獲得了當前正在執行的指令碼的存放路徑。

補充:

scriptPath2是取得軟連線絕對路徑