How do you append to an indirect parameter expansion of an array in BASH?

前端 未结 4 749
孤街浪徒
孤街浪徒 2021-01-14 05:09

I know you can create an indirect parameter expansion to an array like so:

var1=\"target\"
var2=\"arrayname\"
targetarrayname=( \"one\" \"two\" \"three\" )
b         


        
4条回答
  •  一整个雨季
    2021-01-14 06:00

    You can do it with printf

    arrayname=()
    arrayvariable=arrayname
    
    printf -v $arrayvariable[1] "test"
    echo "${arrayname[1]}"
    

    To fill in whole array you can use a for loop

    arrayname=()
    arrayvariable=arrayname
    
    for i in {0..5}; {
        item="$arrayvariable[$i]"
        printf -v $item "test$i"
        echo "${!item}"
    }
    

    Note that quotes are not necessary around var name in printf command because var name can't have spaces, if you try to add var with space in name it'll give you this error

    $ printf -v 'test 1' 'sef'
    bash: printf: `test 1': not a valid identifier
    

提交回复
热议问题