版权声明:请附链接,自由转载 https://blog.csdn.net/kangkanglou/article/details/81943986
使用脚本:
BASE_PATH=$(cd `dirname $0`;pwd)
echo "base_path is $BASE_PATH"
或者
DIR_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
echo "dir_path is $DIR_PATH"
我们在HOME目录下,建立文件夹a,b,在a目录下创建test.sh,在HOME目录下执行test.sh脚本,执行结果如下:
注意,这种方法一般情况都可以正确获取,但如果执行脚本本身是符号链接,那这种方法就不大奏效,我们测试一下,我们在b目录下创建一个符号链接ln_test.sh,指向a目录下的test.sh
执行b目录下的ln_test.sh,得到结果如下:
为了解决符号链接问题,我们可以用以下脚本
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && 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 located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && pwd )"
执行a目录下的test.sh脚本,得到结果如下:
执行b目录下的ln_test.sh,得到结果如下:
https://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within