引用与执行脚本有关的文件 [英] Referring to a file relative to executing script

查看:68
本文介绍了引用与执行脚本有关的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在编写的bash脚本中,我使用source包含配置文件中定义的变量.要执行的脚本是act.sh,而要执行的脚本是source d是act.conf.sh,所以在act.sh中我有:

In a bash script I'm writing, I use source to include the variable defined in a configuration file. The script to be executed is act.sh, while the script to be sourced is act.conf.sh, so in act.sh I have:

source act.conf.sh

但是,这仅在包含它的目录中运行act.sh时有效,因为act.conf.sh引用了放置在工作目录下的文件.有没有一种解决方案可以使它在不调用cd的情况下引用相对于执行脚本的文件?谢谢.

However this only works when running act.sh in the directory containing it, since act.conf.sh there refers to the file placed under the working directory. Is there a solution to make it refer to the file relative to the executing script without invoking cd? Thanks.

推荐答案

请参阅: BASH FAQ条目#28: 如何确定脚本的位置?我想从同一位置读取一些配置文件."

任何解决方案都不可能100%地起作用:

Any solution isn't going to work 100% of the time:

重要的是要意识到,在一般情况下,此问题无法解决.您可能听说过的任何方法以及下面将详细介绍的任何方法都存在缺陷,并且仅在特定情况下有效.首先,不要依赖脚本的位置,尝试完全避免该问题!

It is important to realize that in the general case, this problem has no solution. Any approach you might have heard of, and any approach that will be detailed below, has flaws and will only work in specific cases. First and foremost, try to avoid the problem entirely by not depending on the location of your script!

如果您需要编写非常可重用的工具,那么将正确的路径作为脚本的参数将是最可靠的方法.

If you need to write a very reusable tool, then taking the correct path as a parameter to your script is going to be the most reliable method.

假设您的脚本仅从特定的Shell运行,并且只需要一点点灵活性,则您可能可以放松一些这种偏执狂.看看您的选择还是不错的.人们使用的常见模式特别有问题.

Assuming your script is only going to be run from certain shells, and only with a little bit of flexibility required, you can probably relax some of this paranoia. It is still good to look at your options. There are common patterns that people use that are particularly problematic.

尤其是,FAQ建议避免使用非常常用的$0变量:

In particular, the FAQ recommends avoiding the very commonly used $0 variable:

读取$0的所有内容都不是防弹的,因为$0本身是不可靠的.

Nothing that reads $0 will ever be bulletproof, because $0 itself is unreliable.

作为替代方案,您可以改用$BASH_SOURCE.像这样:

As an alternative, you could use $BASH_SOURCE instead. Something like this:

source "${BASH_SOURCE%/*}/act.conf.sh"

此解决方案也有一些警告.请查看常见问题解答"页面,以了解不同解决方案之间的权衡.他们似乎建议cd$BASH_SOURCE结合使用,以使其对您有用,因为当它无法正确扩展时会出现一个方便的错误情况.

There are some caveats to this solution, too. Check out the FAQ page to see the trade-offs between different solutions. They seem to recommend cd in combination with $BASH_SOURCE in cases where it will work for you, as you get a handy error condition when it fails to expand properly.

这篇关于引用与执行脚本有关的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆