本篇文章為大家展示了Linux中怎么獲取路徑的文件名,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)主營(yíng)安岳網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶App定制開(kāi)發(fā),安岳h5小程序定制開(kāi)發(fā)搭建,安岳網(wǎng)站營(yíng)銷(xiāo)推廣歡迎安岳等地區(qū)企業(yè)咨詢(xún)代碼如下:
[root@dabu.info ]#basename /root/aaa/bbb/dabu.txt
顯示:
代碼如下:
dabu.txt #獲取路徑的文件名
shell腳本中如何獲得腳本文件所在路徑?
方法一:
代碼如下:
[root@dabu.info ]#DIR=$(cd "$(dirname "$0")"; pwd)
[root@dabu.info ]#echo $DIR
但是像這種dirname "$0"這種寫(xiě)法,在遇到source命令時(shí)會(huì)得到錯(cuò)誤的結(jié)果。
方法二:
代碼如下:
[root@dabu.info ]#echo "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
上面一行命令可以獲得腳本的絕對(duì)輪徑,無(wú)論你在何處調(diào)用這個(gè)腳本。
但是如果含有軟鏈接,就無(wú)法使用了。所以,我們?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)行時(shí)上面的命令片段時(shí),則上面的命令不能等到正確的結(jié)果。可以參考關(guān)于$CDPATH 陷阱的文章。想理解它如何其作用的,可以運(yùn)行下面的代碼:
代碼如下:
#!/bin/bash
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'"
上述內(nèi)容就是Linux中怎么獲取路徑的文件名,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。