歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> bash獲取當前正在執行腳本的絕對路徑

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

日期:2017/3/1 15:36:06   编辑:關於Linux
bash獲取當前正在執行腳本的絕對路徑 如題,一般我們寫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的那個文件的名字(沒說是絕對路徑) 下面對比下正確答案: 1 #!/bin/bash 2 echo "scriptPath1: "$(cd `dirname $0`; pwd) 3 echo "scriptPath2: "$(pwd) 4 echo "scriptPath3: "$(dirname $(readlink -f $0)) 結果: 1 june@Win7 192.168.1.100 00:31:24 ~ > 2 pwd 3 /home/june 4 june@Win7 192.168.1.100 00:36:11 ~ > 5 bash shell/a.sh 6 scriptPath1: /home/june/shell 7 scriptPath2: /home/june 8 scriptPath3: /home/june/shell 9 june@Win7 192.168.1.100 00:36:15 ~ > 在此解釋下第一條: dirname $0,取得當前執行的腳本文件的父目錄 cd `dirname $0`,進入這個目錄(切換當前工作目錄) pwd,顯示當前工作目錄(cd執行後的) 由此,我們獲得了當前正在執行的腳本的存放路徑。
Copyright © Linux教程網 All Rights Reserved