0

This question already has an answer here:

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.

marked as duplicate by Barmar, Jeff Schaller, G-Man, Kusalananda bash Feb 1 '18 at 6:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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.

  • Why use eval when you can use an indirect reference? – Barmar Jan 31 '18 at 23:33
1

Here is the solution that worked for me:

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

In bash v4 you can use a "nameref"

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.