2

Consider the code below

#! /bin/bash

declare -a input # unnecessary
declare -a bad
declare -a good # unnecessary

input=('alpha 23' 'bravo 79' 'charlie 12')
echo "input is " ${#input[@]} "long"
for x in "${input[@]}"
do
    bad=$x
    good[ ${#good[@]} ]=$x
    echo 
    echo "added '$x', good is now " ${#good[@]} "long, bad is still " ${#bad[@]} "long"
done

The output is

input is  3 long

added 'alpha 23', good is now  1 long, bad is still  1 long

added 'bravo 79', good is now  2 long, bad is still  1 long

added 'charlie 12', good is now  3 long, bad is still  1 long

According to the man-page for bash ... "When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero."

I clearly don't understand the part in bold because I expected the statement "bad=$x" to auto-increment the index every time it is executed. It doesn't and is assigning to bad[0] every time.

Why isn't it doing what I expected and is there a better way of writing the code than the clumsy line where I assign to good[ .. ]

Haydon Berrow
  • 485
  • 2
  • 6
  • 14
  • see: [Bash: add value to array without specifying a key](http://stackoverflow.com/q/1951506/3776858) – Cyrus Oct 08 '16 at 17:51

2 Answers2

4

The part you quoted relates to assignment, not addition:

array=([0]=zero [1]=one [2]=two)

is equivalent to

array=([0]=zero one two)

which, in fact, is the same as

array=(zero one two)

To add to an array, use +=:

array+=(three)
choroba
  • 231,213
  • 25
  • 204
  • 289
  • That makes more sense now, thanks. If I replace bad=$x in the code above with bad+=("$x") then I get the answer I want. – Haydon Berrow Oct 08 '16 at 20:30
2

choroba has answered my question, the correct code would be

#! /bin/bash

input=('alpha 23' 'bravo 79' 'charlie 12')
echo "input is " ${#input[@]} "long"
for x in "${input[@]}"
do
    output+=("$x")
done

echo "output = (" ${output[@]} ") and is " ${#output[@]} " long "

It is useful for scanning and processing the list of parameters to a script if the parameters have spaces and other awkward characters within them

Haydon Berrow
  • 485
  • 2
  • 6
  • 14