原文鏈接:http://sexywp.com/bash-how-to-get-the-basepath-of-current-running-script.htm
常見的一種誤區,是使用 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的那個文件的名字(沒說是絕對路徑)
下面對比下正確答案:
basepath=$(cd `dirname $0`; pwd)
在此解釋下basepath :
dirname $0,取得當前執行的腳本文件的父目錄 cd `dirname $0`,進入這個目錄(切換當前工作目錄) pwd,顯示當前工作目錄(cd執行后的)
由此,我們獲得了當前正在執行的腳本的存放路徑。