[root@dabu.info ]#basename /root/aaa/bbb/dabu.txt
顯示:
dabu.txt #獲取路徑的文件名
shell腳本中如何獲得腳本文件所在路徑?
方法一:
[root@dabu.info ]#DIR=$(cd "$(dirname "$0")"; pwd)/p>
p>[root@dabu.info ]#echo $DIR
但是像這種dirname "$0"這種寫法,在遇到source命令時會得到錯誤的結(jié)果。
方法二:
[root@dabu.info ]#echo "$( cd "$( dirname "${BASH_SOURCE[0]}" )" pwd )"
上面一行命令可以獲得腳本的絕對輪徑,無論你在何處調(diào)用這個腳本。
但是如果含有軟鏈接,就無法使用了。所以,我們?yōu)榱四苷_解析指向腳本的軟鏈接,可以使用下面的多行命令:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" pwd )"
也可與source,bash -c命令使用
但是,如果你在腳本中使用先cd切換到其他目錄,在運(yùn)行時上面的命令片段時,則上面的命令不能等到正確的結(jié)果??梢詤⒖缄P(guān)于$CDPATH 陷阱的文章。想理解它如何其作用的,可以運(yùn)行下面的代碼:
#!/bin/bash/p>
p> SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $SOURCE == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"