bash shell:获取本脚本存储位置的绝对路径

来源:互联网 发布:jquery ajax json 编辑:程序博客网 时间:2024/06/06 21:06

DIR="$( 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 locateddoneDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
这个方法可以完美解决别名、链接、source、bash -c 等导致的问题。

运行下面一段程序,可帮助理解,具体工作流程:

#!/bin/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" )" && pwd )"if [ "$DIR" != "$RDIR" ]; then  echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'"

将会在终端上,出现如下打印:

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'


http://stackoverflow.com/questions/59895/can-a-bash-script-tell-which-directory-it-is-stored-in


0 0