代码之家  ›  专栏  ›  技术社区  ›  Nikita

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

  •  -1
  • Nikita  · 技术社区  · 7 年前

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

    文件内容:

    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 将更新,变量的值将根据文件内容。

    有人能帮我弄清楚如何做到这一点吗。

    1 回复  |  直到 7 年前
        1
  •  1
  •   EJK    7 年前

    您可以使用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