bash - 引用与执行脚本相关的文件

标签 bash shell

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

source act.conf.sh

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

最佳答案

参见:BASH FAQ entry #28: "How do I determine the location of my script? I want to read some config files from the same place."

任何解决方案都不会 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/

相关文章:

windows - 使用 Cygwin 进行 FFMPEG 构建错误 cmp : command not found

bash - 如何使用 bash 检查一个文件是否为空而另一个文件不处于一种状态

bash - 如何使用 Bash 从一组字符串 B 中过滤出一组字符串 A

linux - 如何在 AWS Linux 上安装 Fish Shell

shell - 如何让 rlwrap 在 Emacs 的 shell/eshell 中工作?

python - 在 SSH/Paramiko 中使用不同的 shell 执行命令/脚本

algorithm - 使用 shell 脚本编写算法简介是个好主意吗

bash - 获取开放端口作为数组

带有检查目录的 Linux 别名

linux - 一个 liner shell 脚本,用于按日期重组文件