0

Given:

export A='TEST_'
export B='VAR'

How would I get the value of $TEST_VAR in this case?

Some more conditions:

  • should work both on sh and bash of the latest versions.
  • should not use any not pre-installed ubuntu dependencies.
  • should be the simplest one liner solution
Stan E
  • 3,396
  • 20
  • 31
  • There is no "latest version" of `sh`, because it's not an actual shell; it's a specification implemented by shells like `bash`, `dash`, `ksh`, etc. – chepner May 13 '15 at 14:36
  • hey you have revised and rejected an edit I recently made [this one](https://stackoverflow.com/questions/51023455/abap-material-number-required-after-skip-first-screen/51029549#51029549) what was the reason you rejected it? –  Jun 27 '18 at 09:39

1 Answers1

2

You can use indirect variable reference:

test_var='foo bar baz'
a='test_'
b='var'
c="${a}${b}"

echo "${c}"
test_var

echo "${!c}"
foo bar baz

PS: You should avoid all uppercase variables in Unix to avoid collision with shell internal variables.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • uppercase is just for showing what I want a bit more clear :) Apparently I came to this solution. But Is there a way I can do it simplier, maybe with the one-liner? – Stan E May 13 '15 at 08:15
  • No I don't think one liner will work here. You have to keep variable name in a separate variable first. – anubhava May 13 '15 at 08:18
  • 2
    @Stanjer All you need is `c="${a}${b}";c=${!c}`. Is that not short enough ? –  May 13 '15 at 08:25
  • Or if you definitely know what will be in the variables you could always use eval `eval echo \$${a}${b}` –  May 13 '15 at 08:33
  • Check the solution with a sh version not linked to bash: I think the eval solution is more portable. – Walter A May 13 '15 at 08:50
  • @WalterA: Question is tagged as `bash` – anubhava May 13 '15 at 08:59
  • @Stanjer: Does it work for you? – anubhava May 13 '15 at 09:11
  • @anubhava: OP also wrote "should work both on sh and bash of the latest versions", so the tag might be incorrect. – Walter A May 13 '15 at 09:19
  • 1
    @WalterA eval has more chance of going wrong though as you can execute arbitary code, so should only be used if `!` indirection is not available. –  May 13 '15 at 09:19
  • @JID Correct, that's why you wrote `if you definitely know what will be in the variables` and I prefer the indirection when that works for the shell(s) the OP is running. – Walter A May 13 '15 at 09:24
  • @Stanjer This is not portable. It won't work in `dash` or `zsh`, for instance, either of which could be used as `/bin/sh`. – chepner May 13 '15 at 14:37