Shell獲取當前正在執(zhí)行腳本的絕對路徑
1. pwd命令
我們看看使用pwd命令能否獲取當前正在執(zhí)行腳本的絕對路徑。該命令的作用是“print name of current/working directory”,真實含義是當前工作目錄,并不是正在執(zhí)行腳本的目錄。
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命令并不能得到正在執(zhí)行腳本的目錄。
2. $0
$0是Bash環(huán)境下的特殊變量,其真實含義是: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,真正執(zhí)行的命令會從一個字符串中讀取,字符串后面如果還有別的參數的話,使用從$0開始的特殊變量引用(跟路徑無關了)
(3)除此以外,$0會被設置成調用bash的那個文件的名字(沒說是絕對路徑)
3. 正解
basepath=$(cd `dirname $0`; pwd)
dirname $0,取得當前執(zhí)行的腳本文件的父目錄
cd `dirname $0`,進入這個目錄(切換當前工作目錄)
pwd,顯示當前工作目錄(cd執(zhí)行后的)
到此這篇關于Shell獲取當前正在執(zhí)行腳本的絕對路徑的文章就介紹到這了,更多相關Shell獲取腳本絕對路徑內容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯系alex-e#qq.com處理。