问题描述
假设:
some.txt
dir
|-cat.sh
使用具有内容cat.sh:
With cat.sh having the content:
cat ../some.txt
然后运行 ./ cat.sh
在运行时
在同一水平上的 DIR
工作正常./ DIR / cat.sh DIR
没有。我希望这是由于不同的工作目录。有一个简单的是使路径 ../ 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 the different working directories. Is there an easy was to make the path ../some.txt
relative to the location of cat.sh
?
推荐答案
您想要做的是通过 $ {BASH_SOURCE [0]} $ C拿到剧本的绝对路径(可$ C>),然后用它来获取父目录和
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}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
这将使独立你来自哪里,它调用你的shell脚本工作。每次运行它的时候,它会像如果你正在运行 ./ cat.sh
在 DIR
。
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)
这篇关于壳牌:基于文件的位置,而不是当前工作目录的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!