2

Is it possible in bash to compose a variable name from some other variable and then ask if a variable whose name is the value of that variable is defined?

a=foo
b=f_$a
if [ -n "${$b}" ] 

where I am looking for a variable of name f_foo. I thought something like ${$b} might do it but that gives bad substitution

  • 1
    Possible duplicate of [Dynamic variable names in Bash](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) – codeforester Jul 20 '17 at 17:27
  • I guess there should be different examples of this question. However, the linked question and answers do not focus on just one variable referring to another. (In the link there is some distraction from getting the variable value from the output of ls.) – Henk Langeveld Jul 21 '17 at 21:09

1 Answers1

3

What you want looks like the ${!var} bash-ishm

b=b_foo
b_foo=bar
echo ${!b}

This is a unique feature to for variable indirection.


Ksh93 has a similar feature typeset -n or its alias nameref with different syntax.

typeset -n b=b_foo
b_foo=bar
echo ${b}

Results in bar as well.

Henk Langeveld
  • 8,088
  • 1
  • 43
  • 57