DaMaxContent DaMaxContent - 6 months ago 23
PHP Question

Variable Variable Storage in Bash

In PHP, you can use a variable value as a reference to another variable by name. I know that there is an equivalent of this in Bash:

$fruit = "banana";

$var_name = "fruit";

echo $$var_name; //Result is banana


which can be found on another question on the stack [here]

but is there an equivalent to this:

$fruit = "banana";

$var_name = "fruit";
$$var_name = "apple"; //<<<this how do I replicate this?

echo $$var_name; //Result is apple //<<<I dont care about this


in bash?

I AM NOT TRYING TO GET VALUE, but STORE IT via VARIABLE VARIABLE!

More clarification:

I need to be able to access variable by its name, not by some array index. I have a function that produces a string. Using some text processing, it assigns var_name a computed string based on the original. I need the variable who's name is that computed string to change in value

Answer

you could try the eval command:

fruit="banana"

var_name="fruit"

eval "$(echo ${var_name})='apple'"

echo ${fruit} //returns apple