从链接目录指向绝对路径

本文介绍了一种在Bash脚本中获取当前脚本绝对路径的方法,包括处理符号链接和别名的情况,并提供了一个多行解决方案来确保无论脚本如何被调用都能正确解析其完整路径。
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, 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用来切换目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值