3

How can I reference a variable in bash based on another variable? Let me setup the example:

package="foobar"

# the variable I wish to reference is $foobar_darwin_amd64
# thus trying:
echo "$package_darwin_amd64"

But this does not work.

0

3 Answers 3

10

If you shell supports the ${!varname} form of indirect references, you can do (as suggested by @Barmar):

$ foobar_darwin_amd64=pinto
$ package=foobar
$ varname="${package}_darwin_amd64"
$ echo ${!varname}
pinto

Otherwise, you can use eval:

$ foobar_darwin_amd64=pinto
$ package=foobar
$ eval echo \$${package}_darwin_amd64
pinto

That said, using eval has some risks associated with it, see this link for more discussion.

1
  • Why use eval when you can use an indirect reference? Commented Jan 31, 2018 at 23:33
2

Here is the solution that worked for me:

VARNAME="${package}_darwin_amd64"
echo "${!VARNAME}"
2

In bash v4 you can use a "nameref"

$ foobar_darwin_amd64=pinto
$ package=foobar
$ declare -n var=${package}_darwin_amd64
$ echo "$var"
pinto

The variable name you constructed can be obtained with the indirect variable expansion syntax:

$ echo "${!var}"
foobar_darwin_amd64

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.