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

?

9

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
    If arr2 is an empty, arr1 becomes an array of length one with one empty string – Andy Oct 17 '16 at 22:10
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[@]}"})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.