- 1. 功能说明
- 2. 相关shell命令
- 2.1 dirname
- 2.2 pwd
- 2.3 readlink
- 3. 最终实现
通过shell脚本启动服务时,往往需要获取到当前脚本的绝对路径,再依据该绝对路径获取一些配置文件、静态库等的路径,为此,在shell脚本中拿到该脚本的绝对路径是很有用的。
2. 相关shell命令 2.1 dirname返回文件目录名:
$ dirname path
例如:
$ dirname /a/b/c # 或者 $ dirname /a/b/c/ /a/b $ dirname a/b/c # 或者 $ dirname a/b/c/ a/b $ dirname a # 或者 $ dirname a/ . $ dirname / # 或者 $ dirname // /2.2 pwd
print working directory:
$ pwd2.3 readlink
打印解析后的符号链接(symbol link)。
SOURCE=$(readlink "$SOURCE")3. 最终实现
#!/usr/bin/env bash SOURCE=$0 # $0 is the shell name, maybe absolute path, relative path or symbolic link while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink 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 )" # script absolute path



