在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
复制代码 代码如下:[[email protected] ]#basename /root/aaa/bbb/dabu.txt 显示: 复制代码 代码如下:dabu.txt #获取路径的文件名
方法一: 复制代码 代码如下:[[email protected] ]#DIR=$(cd "$(dirname "$0")"; pwd)</p>
<p>[[email protected] ]#echo $DIR
但是像这种dirname "$0"这种写法,在遇到source命令时会得到错误的结果。
方法二: 复制代码 代码如下:[[email protected] ]#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'" |
请发表评论