I am using arrays in bash and one particular array is behaving unusually.

I am using a function and calling an external script which returns a value to be appended to an array as follows:

function get_unit_coverage() {

 for sub_unit in "$@"
     extracted_value=$( ./external_script.sh $file $sub_unit )

I pass this function an array and expect the array to be appended each iteration.

However the retun of:

echo "${my_Array[0]}"



The external_script.sh simply echoes these values, is this a potential issue?

  • 1
    Take care on the capitalization also (array vs Array) – Jeff Schaller Mar 7 at 11:45

To append new elements to an array:

array+=( new elements here )

In your case:

my_array+=( "$extracted_value" )

When you do


you are appending to the first element of the array. It is the same as


Also note that in

extracted_value=$( ./external_script.sh $file $sub_unit )

the values $file and $sub_unit will be split on whitespace and undergo filename globbing. To prevent this, use "$file" and "$sub_unit" instead (i.e. double-quote the variable expansions).

Likewise, saying

my_array+=( $extracted_value )

would split the value of $extracted_value into multiple words, and each word would undergo filename globbing to generate new element in the array. That would be better written (as already mentioned),

my_array+=( "$extracted_value" )

This is general advice and there's no reason to not do this regardless of whether you know your values are already single words containing no globbing characters.

  • Is there a formal term for why I was implicitly only appending to the first index? In Python this would work fine, I don't see why the right hand side would make all the difference when the left hand side and operator is constant. – cc6g11 Mar 7 at 14:20
  • @cc6g11 What you want to use is called a compound assignment in the bash manual. That's the name of variable=( ... ) and variable+=( ... ) and is specifically for assigning to or adding to an array. Both variable="..." and variable+="..." are ordinary variable assignments. When an array name is used as just arrayname in an ordinary assignment, you modify its first element. The same goes for using it like echo "$arrayname" instead of echo "${arrayname[@]}" (i.e. only the first element is printed). – Kusalananda Mar 7 at 14:23

You added to a string and read it as an array (as Kusalananda explained well above). But your question shows how a variable can be treated as an array. In fact a simple variable can easily become an array.

$ a+=1
$ a+=2
$ echo "$a"
$ echo "${a[0]}"
$ a+=(3)
$ echo "$a"
$ echo "${a[0]}"
$ echo "${a[1]}"

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.