这是一个有用的单行程序,无论从哪里调用脚本,它都会为您提供脚本的完整目录名称。 ) l2 Y. E2 Z1 U3 o ]( g只要用于查找脚本路径的最后一个组件不是符号链接(目录链接正常),它就会工作。如果您想分析脚本本身的任何链接,您需要更多的解决方案: 1 P" {: Q' A- ~9 S1 s) W3 Z
#!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && 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 locateddoneDIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) 0 S4 |1 y$ t! c" o
#!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; 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 fidoneecho "SOURCE is '$SOURCE'"RDIR=$( dirname "$SOURCE" )DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'"2 v8 x7 R% W$ q
它将打印以下内容: * j* K6 D' n# S4 Y- ]! R* I
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')SOURCE is './sym2/scriptdir.sh'DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'6 X! n" c, B4 O, b