在bash

时间:2017-09-27 23:21:48

标签: bash shell

我的目的是动态地检索表的值,在循环的第一次运行中,t = 1,table的值应该是“table”,并且在第二次运行时应该是“other table”,所以我尝试过使用for循环命名变量,但我的输出是“1”,“2”而不是“table”,“other table”。但是如果我把table = $ TABLENAME $ 1,则输出是“table”。 我无法选择错误,我是shell脚本的新手,如果有任何错误,请原谅,谢谢!!

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

1 个答案:

答案 0 :(得分:1)

正如David C. Rankin在评论中写道,你的脚本应该是这样的:

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

首先,您需要获取变量名称(var_name),然后使用$ {!var_name}将变量名称扩展为其值