基于文件位置而不是当前工作目录的相对路径 [英] Relative paths based on file location instead of current working directory
问题描述
给出:
some.txt
dir
|-cat.sh
cat.sh具有以下内容:
With cat.sh having the content:
cat ../some.txt
然后在dir
内运行./cat.sh
可以正常工作,而在与dir
相同级别上运行./dir/cat.sh
则可以.我希望这归因于不同的工作目录.有没有一种简单的方法可以使路径../some.txt
相对于cat.sh
的位置?
Then running ./cat.sh
inside dir
works fine while running ./dir/cat.sh
on the same level as dir
does not. I expect this to be due to the different working directories. Is there an easy way to make the path ../some.txt
relative to the location of cat.sh
?
推荐答案
您要做的是获取脚本的绝对路径(可通过${BASH_SOURCE[0]}
获得),然后使用它来获取父目录和cd
脚本开头的内容.
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
这将使您的shell脚本独立于您从何处调用它而工作.每次运行它时,就像在dir
中运行./cat.sh
一样.
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
请注意,此脚本仅在您直接调用脚本(即不通过符号链接)时才有效,否则,找到脚本的当前位置会更加棘手)
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
这篇关于基于文件位置而不是当前工作目录的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!