0

How can I access an environment variable from another? I have the following in my shell

#!/usr/bin/env bash

set -x

export A_version=1.0.0

component=A

echo ${${component}_version}}

the bash script after the run gives me

temp.sh: line 9: ${${component}_version}}: bad substitution
6
  • that works if you want to simply echo the content of ${component}_version. now how can I assign the value to another variable. something like b=eval "echo \$${component}_version" ? would that work? Commented Dec 8, 2017 at 0:00
  • actually it looks like version=eval "echo \\$${component}_version" works. Commented Dec 8, 2017 at 0:07
  • Works only if you trust the variable's contents not to be malicious. If component='(rm -rf ~)', then you're in a very bad place when you run that. Other (non-eval-based) parameter expansion syntax doesn't carry those risks. See also BashFAQ #48 re: why eval is generally discouraged. Commented Dec 8, 2017 at 0:10
  • I've looked at the myriad resources you linked to but I can't actually find a working code example for solving the OP's problem that doesn't use eval. How about you post an answer here with one? Commented Dec 8, 2017 at 17:29
  • The alleged duplicates to the this question do not address how one would add a suffix like _version to the variable name before accessing it, so this should be reponed. Commented Dec 8, 2017 at 17:38

1 Answer 1

1

You can use eval to do this. Here is a working version of your script that prints 1.0.0:

export A_version=1.0.0
component=A
eval "echo \$${component}_version"

For more information, see this page:

http://tldp.org/LDP/abs/html/ivr.html

Update: A safer way to do the same thing in Bash would be:

export A_version=1.0.0
component=A
var=${component}_version; echo "${!var}"

Note that you have to run this script with bash, not sh.

Sign up to request clarification or add additional context in comments.

7 Comments

Please don't encourage eval for indirect evaluation, or encourage the ABS as a reference -- it's very much the W3Schools of bash; half of what we do in the freenode #bash channel is help people unlearn bad habits they picked up there. BashFAQ #6 is a reference on indirect variable use that's more actively focused on best practices. The bash-hackers' wiki also covers indirection in its page on parameter expansion.
Searching for "indirect expansion" in the relevant manual page also works.
None of your suggestions seem to solve the OP's problem, how about you post your own answer?
The linked duplicates solve the OP's problem -- see the list at the top of the question. Accordingly, this question has been closed, and is not open to new answers.
How about posting a comment with the code? What exactly would you put on line 3 of my script?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.