将本地Bash文件导入另一个Bash文件

8

我有一个var.sh文件

name="John"
age="29"

我还有一个main.sh文件。

eval "var.sh"
echo "My name is $name"

当我运行时,我一直遇到了
⚡️  Desktop  bash main.sh 
main.sh: line 1: var.sh: command not found
My name is 

如何将本地bash文件导入另一个bash文件是最佳实践?

是否有一种方法适用于Mac OS X、Linux和Windows?

1个回答

10

eval 不适用于将一个脚本导入到另一个脚本中。你需要使用内置的 source 函数:

source var.sh

这与...同义:

. var.sh

eval抛出错误的原因可能是以下两个之一:

  • var.sh不是可执行文件
  • var.sh虽然是可执行文件,但当前目录不在PATH中

即使我们解决了这两个问题,eval仍会生成一个shell来运行var.sh,这意味着所有在var.sh中设置的变量在eval完成后都被遗忘了,这并不是你想要的。


help source命令的输出:

source: source filename [arguments]

Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

请给我点踩的人,请告诉我这个答案有什么问题。 - codeforester
我不是那个给你的回答点踩的人,只是想让你知道。 - code-8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接