0

I have an array

declare -a her=("ger" "blr" "tyg" "")

for i in "${her[@]}"; do
    echo $i
done

I get

ger
blr
tyg

But when I try and append to an array I get one long string with no spaces

declare -a you

#without quotes and with quotes
#' " same result

for i in {"fgt","fe","ger"}; do
    you+=${i}
done

for i in "${you[@]}"; do
    $i
done

Fgtfeger

Any insight on whats happening ? Kinda makes them not as useful

3
  • 4
    Would be you+=("${i}"). – schrodigerscatcuriosity Sep 13 '20 at 23:17
  • Use declare -p you for additional clues. – glenn jackman Sep 14 '20 at 2:58
  • thanks for the tips. these arrays are newer to me at least in bash. – ssvegeta96 Sep 15 '20 at 16:08
4

Use Array Compound Assignment Syntax; Otherwise Use Length as Index

You have to append to an array using either the compound assignment syntax (e.g. foo=("elem1" ...) or an array index.

Array Compound Assignment Syntax

The form with parentheses allows you to insert one or more elements at a time, and is (arguably) easier to read. For example:

# start with a clean slate
unset you

for i in "fgt" "fe" "ger"; do
    you+=("$i")
done

printf "%s\n" "${you[@]}"

This yields the values you'd expect:

fgt
fe
ger

Insert at Index Length

You can get similar results by assigning to an index. For example:

unset you
for i in "fgt" "fe" "ger"; do
    you[${#you[@]}]="$i"
done
printf "%s\n" "${you[@]}"

This second example works because Bash arrays are zero-indexed, so the length of the array is also the next available index that should be assigned when appending.

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.