10

I was expecting

excludes="${excludes:-( ${default_excludes[@]} )}"

to be an array if $excludes is empty. Unfortunately the stuff after :- is taken to be a string. Did I miss some syntax contortion, or do I have to use the clunky

if [ -z "${excludes:-}" ]
then
    excludes=( "${default_excludes[@]}" )
fi

?

0

2 Answers 2

12

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.

2
  • 3
    If arr2 is an empty, arr1 becomes an array of length one with one empty string
    – Andy
    Commented Oct 17, 2016 at 22:10
  • if you need to use this in combo with incoming script parameters, use: main_args=( "${@:-${default_args[@]}}") Note the lack of brackets on the first@
    – TonyH
    Commented Oct 21, 2021 at 17:21
2

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[@]}"})

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .