【问题标题】:Import a local bash file into another bash file [duplicate]将本地 bash 文件导入另一个 bash 文件[重复]
【发布时间】:2019-07-16 01:04:49
【问题描述】:
我有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 上运行的方法?
【问题讨论】:
标签:
linux
bash
macos
shell
unix
【解决方案1】:
eval 并不意味着将脚本导入另一个脚本。你需要 source 内置:
source var.sh
这就是:
. var.sh
eval 抛出错误是由于以下一个或两个原因:
- var.sh 不可执行
- var.sh 是可执行文件,但当前目录不在 PATH 中
即使我们解决了这两个问题,eval 也会生成一个 shell 来运行 var.sh,这意味着一旦 eval 完成,var.sh 中设置的所有变量都会被遗忘,这不是你想要的。
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.