0

My intention is to retrieve the value of the table dynamically, in the first run of the loop where t=1, value of table should be "table" and should be "other table" in the second run, so i tried to name the variable using for loop, but my output is "1","2" instead of "table","other table".But if I put table=$TABLENAME$1, output is "table". I couldn't pick the error, I am new to shell scripting, excuse if there is any blunder, thank you!!

 TABLENAME1="table"
 TABLENAME2="other table"
 NUM_TABLE=2
 for (( t = 1; t <= ${NUM_TABLE}; t++ )){
 table=$TABLENAME$t
 echo $table
 }
  • 1
    `foobar=1; foobaz=2; a=foo; b=bar; c=baz; d=$a$b; echo ${!d}; d=$a$c; echo ${!d}` In you case `echo ${!table}` – David C. Rankin Sep 27 '17 at 23:53
  • Thanks for your explanation David, I got your point. –  Sep 28 '17 at 00:06
  • BTW, this is covered comprehensively in [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006), including discussing ways to avoid having the problem in the first place (with associative arrays and other structures as alternatives). – Charles Duffy Sep 28 '17 at 00:29

1 Answers1

1

As David C. Rankin wrote in his comment, you script should look like this:

TABLENAME1="table"
TABLENAME2="other table"
NUM_TABLE=2
for (( t = 1; t <= ${NUM_TABLE}; t++ )){
    var_name="TABLENAME"$t
    echo ${!var_name}
}

First, you need to get variable name (var_name) and then use ${!var_name} to expand variable name to its value

Maxim Norin
  • 1,343
  • 2
  • 9
  • 12
  • Thank you Maxim for your explanation, now it made sense to me. –  Sep 28 '17 at 00:07
  • Heh. At first I thought you *were* David Rankin, and was about to chide you for answering a duplicate rather than flagging it as such (as described in [How to Answer](https://stackoverflow.com/help/how-to-answer)). Folks who are new and don't know what the FAQs are get more leniency there though. :) – Charles Duffy Sep 28 '17 at 00:31