Setting environment variables for a script in a local bash function variable

I have a Unix bash function that runs a script that parses user environment variables. I do not want to export the corresponding variables in bash, but instead set them only for the script, as part of the execution command.

If I set the variables directly in the command - for example VARNAME=VARVAL script_name- this works well. However, since I want to set several variables based on different conditions, I want to use a local function variable to store the parameters of the environment variable, and then use this variable in the script execution command. I have a local variable "vars" that is ultimately set, for example, to VARNAME=VAR, but if I try to run ${vars} script_namebash from my function, I get a "command not found" error for the variable $ vars assignment - that is, the contents of $ vars are interpreted as a team, not as an assignment of environment variables.

I tried different options for command syntax, but so far to no avail. Currently, I have to export the corresponding variables to the function before calling the script, and then unset / reset them to the previous values, but this is not quite the solution I was hoping for.

Any help would be greatly appreciated.

Thanks Sharon

+5
source share
2 answers

To evaluate the contents of your variables as an expression, not as a command, you can try using eval:

eval ${vars} script_Name
+3
source

, , , , script .

. :

$ cat test.sh 
#!/usr/bin/env bash
echo "$foo"
echo "$bar"
$ foo=abc bar=def ./test.sh 
abc
def

, eval.

+2

All Articles