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 )"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
This last one will work with any combination of aliases, source, bash
-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用来切换目录
本文介绍了一种在Bash脚本中获取当前脚本绝对路径的方法,包括处理符号链接和别名的情况,并提供了一个多行解决方案来确保无论脚本如何被调用都能正确解析其完整路径。
1577

被折叠的 条评论
为什么被折叠?



