从链接目录指向绝对路径

来源:互联网 发布:罗素 知乎 数学家 编辑:程序博客网 时间:2024/06/07 06:26
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Is a useful one-liner which will give you the full directory name of the script no matter where it is being called from

表示有一种链接的情况。

============================================================================================

Or, to get the dereferenced path (all directory symlinks resolved), do this:

DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

These will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you want to also resolve any links to the script itself, you need a multi-line solution:

SOURCE="${BASH_SOURCE[0]}"DIR="$( dirname "$SOURCE" )"while [ -h "$SOURCE" ]do   SOURCE="$(readlink "$SOURCE")"  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"  DIR="$( cd -P "$( dirname "$SOURCE"  )" && pwd )"doneDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

This last one will work with any combination of aliases, sourcebash -c, symlinks, etc.

多重链接的情况


等同下面的脚本:

SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd > /dev/null


pushd、popd用来切换目录