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

时间:2019-02-22 01:04:37

标签: linux bash macos shell unix

我有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 个答案:

答案 0 :(得分:0)

eval并不意味着将脚本导入另一个脚本。您需要内置source

source var.sh

等同于:

. var.sh

eval出于以下两个或多个原因引发错误:

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

即使我们同时解决了这两个问题,eval也会产生一个运行var.sh的shell,这意味着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.