复制代码代码如下: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""