在我编写的 bash 脚本中,我使用 source
来包含配置文件中定义的变量。要执行的脚本是act.sh
,而要作为source
d的脚本是act.conf.sh
,所以在 act.sh
我有:
source act.conf.sh
然而,这仅在包含它的目录中运行 act.sh
时有效,因为 act.conf.sh
指的是放置在工作目录下的文件。有没有一种解决方案可以使其在不调用 cd
的情况下引用与执行脚本相关的文件?谢谢。
最佳答案
任何解决方案都不会 100% 有效:
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!
如果您需要编写一个非常可重用的工具,那么将正确的路径作为脚本的参数将是最可靠的方法。
假设您的脚本只会从特定的 shell 运行,并且只需要一点灵 active ,那么您可能会放松一些这种偏执狂。看看您的选择仍然很好。人们使用的一些常见模式特别有问题。
特别是,常见问题解答建议避免使用非常常用的 $0
变量:
Nothing that reads
$0
will ever be bulletproof, because$0
itself is unreliable.
作为替代方案,您可以改用 $BASH_SOURCE
。像这样:
source "${BASH_SOURCE%/*}/act.conf.sh"
此解决方案也有一些注意事项。查看常见问题解答页面,了解不同解决方案之间的权衡。他们似乎建议将 cd
与 $BASH_SOURCE
结合使用,因为当它无法正确扩展时,您会得到一个方便的错误条件。
关于bash - 引用与执行脚本相关的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6659689/