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}").CommentedSep 13, 2020 at 23:17
  • Use declare -p you for additional clues.CommentedSep 14, 2020 at 2:58
  • thanks for the tips. these arrays are newer to me at least in bash.CommentedSep 15, 2020 at 16:08

1 Answer 1

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.

    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.