1. 功能说明
通过shell脚本启动服务时,往往需要获取到当前脚本的绝对路径,再依据该绝对路径获取一些配置文件、静态库等的路径,为此,在shell脚本中拿到该脚本的绝对路径是很有用的。
2. 相关shell命令
2.1 dirname
返回文件目录名:
$ dirname path
例如:
$ dirname /a/b/c
/a/b
$ dirname a/b/c
a/b
$ dirname a
.
$ dirname /
/
2.2 pwd
print working directory:
$ pwd
2.3 readlink
打印解析后的符号链接(symbol link)。
SOURCE=$(readlink "$SOURCE")
3. 最终实现
#!/usr/bin/env bash
SOURCE=$0
while [ -h "$SOURCE" ]; do
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$SCRIPT_DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
|