user2953466
user2953466

Reputation: 51

Bash variable lookup

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

Upvotes: 2

Views: 53

Answers (1)

Henk Langeveld
Henk Langeveld

Reputation: 8446

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.

Upvotes: 3

Related Questions