bash: 创建一个包含另一个变量的变量名

bash: create a variable name containing another variable

我在读取 bash 中的文件时必须创建多个变量。 根据文件的内容,这些变量需要有一个动态名称。 例如:

文件内容:

abc: 20
1 apple a day
abc: 40
1 keeps the doctor away

现在我必须将变量创建为:

day_20_id = 1
day_20_fruit = apple
away_40_id = 1
away_40_who = doctor

就像在所有变量名中一样,只有$abc的值会被更新,变量的值将根据文件内容。

谁能帮我弄清楚如何实现这一目标。

您可以使用 eval 命令完成此操作,如下图所示

abc=20  # assuming you got this from the input file
val=1   # assuming you also got this from the input file

varName="day_${abc}_id"
command="${varName}=${val}"
eval $command

# now print to output file as you have stated in the comments
outputFile=output.txt  # randomly-chosen name
command="echo $varName = $val > $outputFile"
eval $command