Write default array to variable in Bash

You can construct an array from another array with this syntax:

arr1=( "${arr2[@]}" )

That can be translated into this default-value syntax:

arr1=("${arr1[@]:-${arr2[@]}}")

I've tested some edge cases, like array members with spaces or newlines in them and it seems to handle them correctly.


Since I had cases where my arr2 might be empty, but set, I could not find a simple solution. So I had to go with a function and global temp variable. But it works in every case and in bash 3.2 and bash 4

function set_temp_array()
{ # 1 - source_array_name $2-* default_values
  local default="$1"
  shift
  if declare -p $default >& /dev/null; then
    default="${default}[@]"
    TEMP_VAR=("${!default}")
  else
    TEMP_VAR=("${@}")
  fi
}

set_temp_array arr1 "${arr2[@]}"
arr1="${TEMP_VAR[@]}"

I use indirect array reference to copy the values to TEMP_VAR, but I couldn't figure out an indirect array assignment in bash, hence the two lines and temp variable

For you set -eu fans out there

function set_temp_array()
{ # 1 - source_array_name $2-* default_values
  local default="$1"
  shift
  if declare -p $default >& /dev/null; then
    default="${default}[@]"
    TEMP_VAR=(${!default+"${!default}"})
  else
    TEMP_VAR=(${@+"${@}"})
  fi
}

set_temp_array arr1 ${arr2+"${arr2[@]}"}
arr1=(${TEMP_VAR+"${TEMP_VAR[@]}"})

Tags:

Bash

Array