0

I'm trying to get the values of some php variables into a bash script in order to set other bash variables. Basically I need to be able to access the value of a variable - variable name.

the script can find & read the file, find the php variables, but when I try to set them it just hangs. Here is what I have:

variables=(database_user database_password dbase);

paths=(modx_core_path modx_connectors_path modx_manager_path modx_base_path);

for index in "${variables[@]}"; do
index=\$$index
echo $index;
$index="$(grep -oE '\$${!index} = .*;' $config | tail -1 | sed 's/$${!index} = //g;s/;//g')";
done

not sure what I am doing wrong here...

1
  • @123, please don't suggest the ABS as a reference; it's rather infamous for showcasing bad practices. BashFAQ #6 is a much more up-to-date and actively maintained discussion of indirect variables. Commented Feb 8, 2017 at 21:49

1 Answer 1

2

You are trying to perform an indirect assignment.

You should get rid of these two lines :

index=\$$index
echo $index;

By simply writing :

echo "${!index}"

Which does an indirect expansion cleanly (gives you the value of the variable whose name is contained in variable index).

Next, the problematic line is this one:

$index="$(grep -oE '\$${!index} = .*;' ... (rest omitted)

In Bash, an assignment cannot begin with a $.

One way you can perform an indirect assignment is this (after removing the index re-assignment as suggested above) :

printf -v "$index" "$(grep -oE '\$${!index} = .*;' ... (rest omitted)

This uses the -v option of printf, which causes the value passed as the final argument to be assigned to a variable, the name of which is passed to the -v option.

There are other ways of handling indirect assignment/expansions, some with code injection risks, as they use (potentially uncontrolled) data as code. This is something you may want to research further.

Please note I am assuming the actual grep command substitution works (I have not tested).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.