简体   繁体   中英

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

I got two variables in a bash script. 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. 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

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? 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 ).

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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