1

I know that I can use an existing array as the default value for a variable that is potentially uninitialized via

default_values=(1 2 'value is a string')
array=("${array[@]-${default_values[@]}}")

as already answered in, for example, https://unix.stackexchange.com/a/195979/556459.

What I want to know instead is if I can assign such a default array to a variable by specifying its values explicitly instead of introducing a helper array such as default_values?

The fact that assigning an array to a variable via array=(value1 ...) is called a compound assignment by the Bash Reference Manual for Arrays strongly suggests that it is special syntax and that I cannot simply create array literals by using the (value1 ...) syntax for the value to be substituted in a shell parameter expansion. While trying that indeed fails, maybe there is some alternative that I have missed?

3
  • 2
    nhh, I think ${array-...} there is the same as ${array[0]-...} (as usual), and only tests one element of the array. If the array is sparse, it can trash existing values. Anyway, relying on [@] working properly on the right side of ${var-value} also seems like something I wouldn't want to count on... Why not just if [ "${#array[@]}" = 0 ]; then array=(some default values); fi ? Commented Jul 14, 2023 at 17:39
  • Ah, my bad, I forgot the [@] in my above example. I'll edit my question shortly to correct that. (It's there in the linked answer though.) I'm aware that using as imply if-statement would be an option (just like using a separate variable) but it would be "neater" if I could get this to work using some form of shell expansion instead. Commented Jul 15, 2023 at 7:26
  • Question is updated and in my previous comment "using as imply if-statement" was supposed to read "using a simple if-statement", but I cannot edit a comment after five minutes. Commented Jul 15, 2023 at 7:33

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.