LINUX

关注公众号 jb51net

关闭
操作系统 > LINUX >

Linux系统中获取路径的文件名的方法

脚本之家


[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命令时会得到错误的结果。

 

方法二:


[root@dabu.info ]#echo "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

上面一行命令可以获得脚本的绝对轮径,无论你在何处调用这个脚本。
但是如果含有软链接,就无法使用了。所以,我们为了能正确解析指向脚本的软链接,可以使用下面的多行命令:

   

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切换到其他目录,在运行时上面的命令片段时,则上面的命令不能等到正确的结果。可以参考关于$CDPATH 陷阱的文章。想理解它如何其作用的,可以运行下面的代码:

   

#!/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'"