shell獲取當前工做目錄絕對路徑

通常咱們寫Shell腳本的時候,都傾向使用絕對路徑,這樣不管腳本在什麼目錄執行,都應該起到相同的效果,可是有些時候,咱們設計一個軟件包中的工具腳本或者遠程調用某個腳本時,可能使用相對路徑更加靈活一點,由於你不知道用戶會在哪一個目錄執行你的程序,因而問題就來了,如何獲取當前正在執行腳本的絕對路徑?python

常見的一種誤區,是使用 pwd 命令,該命令的做用是「print name of current/working directory」,這纔是此命令的真實含義,當前的工做目錄,這裏沒有任何意思說明,這個目錄就是腳本存放的目錄。因此,這是不對的。你能夠試試bash shell/a.sh,a.sh 內容是 pwd,你會發現,顯示的是執行命令的路徑 /home/ljl,並非 a.sh 所在路徑:/home/ljl/shell/a.shshell

另外一個誤人子弟的答案,是 $0,這個也是不對的,這個$0是Bash環境下的特殊變量,其真實含義是: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開始的特殊變量引用(跟路徑無關了)this

除此之外,$0會被設置成調用bash的那個文件的名字(沒說是絕對路徑)spa

簡單介紹一下獲取方法以下:設計

#!/bin/bashthis_dir=`pwd`echo "$this_dir ,this is pwd"echo "$0 ,this is \$0"dirname $0|grep "^/" >/dev/nullif [ $? -eq 0 ];then
    this_dir=`dirname $0`else
    dirname $0|grep "^\." >/dev/null
     retval=$?if [ $retval -eq 0 ];then
    this_dir=`dirname $0|sed "s#^.#$this_dir#"`else
    this_dir=`dirname $0|sed "s#^#$this_dir/#"`fi
 fi
 echo $this_dir

總結一下其實就是一條命令:code

base_dir=$(cd "$(dirname "$0")";pwd)
dirname 
$0
,取得當前執行的腳本文件的父目錄
cd 
dirname $0
,進入這個目錄(切換當前工做目錄)
pwd,顯示當前工做目錄(cd執行後的)


我今天遇到一個問題就是:orm

須要壓縮備份一個目錄下的全部的文件,其實代碼就2行:

我仍是貼所有的吧,最後2行是個人:

#!/bin/bash
this_dir=`pwd`
echo "$this_dir ,this is pwd"
echo "$0 ,this is \$0"
dirname $0|grep "^/" >/dev/null
if [ $? -eq 0 ];then
    this_dir=`dirname $0`
else
    dirname $0|grep "^\." >/dev/null
     retval=$?
if [ $retval -eq 0 ];then
    this_dir=`dirname $0|sed "s#^.#$this_dir#"`
else
    this_dir=`dirname $0|sed "s#^#$this_dir/#"`
fi
 fi
 echo $this_dir
date=`date +%Y%m%d%H%M` 
tar -czvf /root/test/FTP_DATA_$date.tar.gz /FTP_DATA

如上,若是不加上邊的,當你執行shell腳本的時候,會報找不到文件,加上以後就行了,你們一塊兒討論學習

相關文章
相關標籤/搜索