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

前端 未结 4 784
孤街浪徒
孤街浪徒 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:50

    With Bash 3.2 Compatibility

    It avoids substantial security bugs to run all values through printf %q to ensure that they're safely escaped before substituting them into eval content.

    #!/bin/bash
    
    appendToArray() {
      local _targetArrayName _argumentData _cmd
      _targetArrayName=$1; shift || return
      printf -v _argumentData '%q ' "$@"
      printf -v _cmd '%q+=( %s )' "$_targetArrayName" "$_argumentData"
      eval "$_cmd"
    }
    
    target=( "first item" "second item" )
    appendToArray target "third item" "fourth item"
    declare -p target
    

    ...correctly emits as output:

    declare -a target=([0]="first item" [1]="second item" [2]="third item" [3]="fourth item")
    

    For Bash 4.3+ Only

    #!/bin/bash
    
    appendToArray() {
      declare -n _targetArray=$1; shift
      _targetArray+=( "$@" )
    }
    
    target=( "first item" "second item" )
    appendToArray target "third item" "fourth item"
    declare -p target
    

    ...has identical output, with much less (and much simpler) code.

提交回复
热议问题