简体   繁体   English

如何调用bash函数提供存储在Bash数组中的环境变量?

[英]how to call a bash function providing environment variables stored in a Bash array?

I got two variables in a bash script. 我在bash脚本中得到了两个变量。 One contains the name of a function within the script while the other one is an array containing KEY=VALUE or KEY='VALUE WITH SPACES' pairs. 一个包含脚本中函数的名称,而另一个是包含KEY=VALUEKEY='VALUE WITH SPACES'对的数组。 They are the result of parsing a specific file, and I can't change this. 它们是解析特定文件的结果,我无法改变它。

What I want to do is to invoke the function whose name I got. 我想要做的是调用我的名字的函数。 This is quite simple: 这很简单:

# get the value for the function
myfunc="some_function"
# invoke the function whose name is stored in $myfunc
$myfunc

Consider the function foo be defined as 考虑将函数foo定义为

function foo
{
   echo "MYVAR: $MYVAR"
   echo "MYVAR2: $MYVAR2" 
}

If I get the variables 如果我得到变量

funcname="foo"
declare -a funcenv=(MYVAR=test "MYVAR2='test2 test3'")

How would I use them to call foo with the pairs of funcenv being added to the environment? 如何在将funcenv添加到环境中的情况下使用它们来调用foo A (non-variable) invocation would look like (非变量)调用看起来像

MYVAR=test MYVAR2='tes2 test3' foo

I tried to script it like 我试着像它一样编写脚本

"${funcenv[@]}" "$funcname"

But this leads to an error ( MYVAR=test: command not found ). 但这会导致错误( MYVAR=test: command not found )。

How do I properly call the function with the arguments of the array put in its environment (I do not want to export them, they should just be available for the invoked function)? 如何使用放在其环境中的数组的参数正确调用该函数(我不想导出它们,它们应该只用于调用的函数)?

You can do like this: 你可以这样做:

declare -a funcenv=(MYVAR=test "MYVAR2='test2 test3'")
for pairs in "${funcenv[@]}"; do
    eval "$pairs"
done
"$funcname"

Note however that the variables will be visible outside the function too. 但请注意,变量在函数外部也是可见的。 If you want to avoid that, then you can wrap all the above in a (...) subshell. 如果你想避免这种情况,那么你可以将所有上述内容包装在(...)子shell中。

why don't you pass them as arguments to your function? 为什么不将它们作为参数传递给你的函数?

function f() { echo "first: $1";  echo "second: $2"; }

fn=f; $fn oneword "two words"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM