bash shell:获取本脚本存储位置的绝对路径
来源:互联网 发布:jquery ajax json 编辑:程序博客网 时间:2024/06/06 21:06
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"无论脚本从哪里调用,怎么调用,上面代码都是非常有用的获得脚本存储位置绝对路径的一行代码。
如果不涉及链接文件,那么它将工作的非常好,可以得到正确的路径。想解决链接文件,就得使用多行代码了:
SOURCE="${BASH_SOURCE[0]}"while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" && 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 locateddoneDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
这个方法可以完美解决别名、链接、source、bash -c 等导致的问题。运行下面一段程序,可帮助理解,具体工作流程:
#!/bin/bashSOURCE="${BASH_SOURCE[0]}"while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET="$(readlink "$SOURCE")" if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE="$TARGET" else DIR="$( dirname "$SOURCE" )" echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fidoneecho "SOURCE is '$SOURCE'"RDIR="$( dirname "$SOURCE" )"DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'"
将会在终端上,出现如下打印:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')SOURCE is './sym2/scriptdir.sh'DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
http://stackoverflow.com/questions/59895/can-a-bash-script-tell-which-directory-it-is-stored-in
0 0
- bash shell:获取本脚本存储位置的绝对路径
- bash shell 获取当前正在执行脚本的绝对路径
- bash shell 获取当前正在执行脚本的绝对路径
- bash shell:获取当前脚本的绝对路径(pwd/readlink)
- bash shell 获取当前绝对路径
- [shell]获取当前脚本的绝对路径
- Shell脚本——获取脚本所在的绝对路径
- shell 获取当前正在执行的脚本的绝对路径
- [转]linux shell 获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- Linux Shell下获取当前脚本的绝对路径
- [Shell]获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- linux shell 获取当前正在执行脚本的绝对路径
- Shell中获取脚本所在目录绝对路径的方法
- 编程规范与范例
- 可以上谷歌学术网站的方法
- windows新建.文件
- 20161105
- 笔记
- bash shell:获取本脚本存储位置的绝对路径
- 第11周项目1-验证算法(3)中序线索化二叉树的算法验证
- 打造你的私人聊天机器人
- Spring Bean之JavaConfig自动化装配bean
- Volley基本使用及源码解析
- poj3276(开关问题)
- 《科比传》留下深刻印象的文字
- Leetcode-32. Longest Valid Parentheses
- cs231n:assignment1——Q1: k-Nearest Neighbor classifier(自动生成版)