且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

引用与执行脚本有关的文件

更新时间:2023-12-04 18:51:34

请参阅: 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.