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

前端 未结 4 788
孤街浪徒
孤街浪徒 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 05:55

    #!/bin/bash
    
    var1="target"
    var2="arrayname"
    targetarrayname=( "one" "two" "three" )
    builtarrayname="${var1}${var2}[@]"
    echo ${!builtarrayname} # prints "one two three"
    
    eval "${builtarrayname:0:-3}+=( 'foo' )"
    
    echo ${!builtarrayname} # prints "one two three foo"
    

    Do note though that eval could be considered evil :p You need to be sure that you only have sanitized input to eval statements, to avoid the possibility of unintended code execution.

    EDIT:

    The :0:-3 in eval "${builtarrayname:0:-3}+=( 'foo' )" removes [@] from the literal string that $builtarrayname contains. Since assignment of arrays only use the variable name, we had to remove it. ( read more here to see how string manipulation in variables work )

    and no, I don't think it can be done without eval, as that's how the left side of the assignment gets resolved before the assignment occurs (see this nice answer for more info on eval.

提交回复
热议问题