在本地 bash 函数变量中为脚本设置环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8877440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting environment variables for a script in a local bash function variable
提问by Sharon
I have a Unix bash function that executes a script that parses custom environment variables. I want to avoid exporting the relevant variables in the bash, and instead set them only for the script, as part of the execution command.
我有一个 Unix bash 函数,它执行一个解析自定义环境变量的脚本。我想避免在 bash 中导出相关变量,而是仅将它们设置为脚本,作为执行命令的一部分。
If I set the variables directly in the command -- e.g., VARNAME=VARVAL script_name-- it works well. However, since I want to set multiple variables, based on different conditions, I want to use a local function variable to store the environment variable settings, and then use this variable in the script execution command.
I have a local "vars" variable that is ultimately set, e.g., to VARNAME=VAR, but if I try to run ${vars} script_namefrom my bash function, I get a "command not found"error for the $vars variable assignment -- i.e., the content of $vars is interpreted as a command instead of as environment variables assignment.
如果我直接在命令中设置变量——例如VARNAME=VARVAL script_name——它运行良好。但是,由于我要设置多个变量,根据不同的条件,我想使用一个局部函数变量来存储环境变量设置,然后在脚本执行命令中使用这个变量。我有一个最终设置的本地“vars”变量,例如,to VARNAME=VAR,但是如果我尝试${vars} script_name从我的 bash 函数运行,我会收到$vars 变量赋值的“command not found”错误——即$vars 被解释为命令而不是环境变量赋值。
I tried different variations of the command syntax, but so far to no avail. Currently I have to export the relevant variables in the function, before calling the script, and then unset/reset them to the previous values, but this is not really the solution I was hoping for.
我尝试了命令语法的不同变体,但到目前为止都无济于事。目前我必须在调用脚本之前导出函数中的相关变量,然后将它们取消设置/重置为以前的值,但这并不是我真正希望的解决方案。
Any help would be greatly appreciated.
任何帮助将不胜感激。
Thanks, Sharon
谢谢,莎伦
采纳答案by jcollado
回答by l0b0
However, since I want to set multiple variables, based on different conditions, I want to use a local function variable to store the environment variable settings, and then use this variable in the script execution command.
但是,由于我要设置多个变量,根据不同的条件,我想使用一个局部函数变量来存储环境变量设置,然后在脚本执行命令中使用这个变量。
You don't need to store the variables in a separate variable. You can assign more than one variable for a command:
您不需要将变量存储在单独的变量中。您可以为一个命令分配多个变量:
$ cat test.sh
#!/usr/bin/env bash
echo "$foo"
echo "$bar"
$ foo=abc bar=def ./test.sh
abc
def
This also has the advantage of being safer than eval.
这也具有比 更安全eval的优点。

