WX_M
WX_M

Reputation: 488

Call variable from within variable

I have a source file which contains several libraries for names of variables. For example:

qvs_var1="ABC1"
qvs_var2="LMN2"
qvs_var3="LNE5"
qvs_var4="RST2"
....

Loading in the source file at the beginning of another file with:

source lib_file.csh

I now have access to the variables listed above. I want to access them dynamically and sequentially from a file prompting the variables to process. For example:

# Load in source file
source lib_file.csh

# Read in variables to process
vars=$(<variables_to_process.txt)

# For this example, vars = var1 var3

# Begin looping
For var in ${vars}
do
  echo ${qvs_${var}}
done

Where the output should be: ABC1, and then LNE5. The error in the echo line above prompts: 'bad substitution'. What is the proper format to achieve what is needed?

Upvotes: 1

Views: 1685

Answers (1)

kvantour
kvantour

Reputation: 26571

What you are after is called indirection:

${parameter} The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character which is not to be interpreted as a part of its name.

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of the parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

source: man bash

Below you find a simple example:

$ foo_1="car"
$ bar="1"

We are now interested in printing the value of foo_1 using bar:

$ tmpvar="foo_$bar"
$ echo ${!tmpvar}
car

Upvotes: 2

Related Questions