0

Help! I can't figure this out for the life of me!

I have:

m=5
eval TEST_m="dog"

If I do:

echo $TEST_5 >> "dog"

I'm trying to find a way to echo "$TEST_$m" and get "dog"; I've tried these, but they all just return the value of $m which is 5.

echo $TEST_$m >> 5
echo $TEST_${m} >> 5
eval "echo $TEST_${m}" >> 5

Thanks!

  • 1
    What you want is called indirect expansion. See [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006). – Charles Duffy Aug 22 '17 at 15:22
  • Unsure, but would `$()` be helpful in this situation? – dǝɥɔS ʇoıןןƎ Aug 22 '17 at 15:24
  • 2
    (BTW -- in almost all cases, if you think `eval` is the answer, you're asking the wrong question; see also [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048)). – Charles Duffy Aug 22 '17 at 15:24
  • 1
    @ratskin, no, command substitution is not particularly helpful in this situation -- there's nothing it provides that's immediately applicable that you couldn't do more efficiently without it. Parsing happens **before** command substitution happens unless a new parse phase is kicked off with `eval`, and if you're kicking off a new parse phase, you (1) don't need the command substitution anyhow, and (2) just introduced a bunch of potential security bugs. – Charles Duffy Aug 22 '17 at 15:24
  • Yes, I see that now. Didn't understand the question properly. Thanks – dǝɥɔS ʇoıןןƎ Aug 22 '17 at 15:26
  • Hey Charles, I believe I worked with you at Indeed a couple years back. I remember you had a rep for being a master of bash! I suspect you're right about 'eval', but its the only way I've found to save a bunch of variables in a for loop (eval var_$m="test"; where 'm' increments to var_1, var_2, var_3, var_4 etc) – Matt Rhyner Aug 22 '17 at 15:38
  • @MattRhyner, heh -- yup, that's me. Sounds like your better approach would actually be to make `var` be an array. `var=( ); var[1]=foo; var[2]=bar` – Charles Duffy Aug 22 '17 at 15:52
  • @MattRhyner, ...that's covered in the first (#6) FAQ I linked; *do* give it a read. – Charles Duffy Aug 22 '17 at 15:57

0 Answers0