Skip to main content
3 of 3
mention potential issues with sparse arrays.
Stéphane Chazelas
  • 584.9k
  • 96
  • 1.1k
  • 1.7k

The += operator appeared in Bash version 3.1.

  • In older versions, if the array is not sparse, you can either assign to the element after the array's last element:

      NODES[${#NODES[@]}]="$WAS_IP"
    

    If you append new values in one certain place, you may use a separate counter variable:

      NODES=()
      NODES_length=0
      NODES[NODES_length++]="$WAS_IP"
    

    But this is just moderately faster than asking the array's length with ${#NODES[@]}.

  • Or you can assign the whole array to the existing elements and the new one:

      NODES=("${NODES[@]}" "$WAS_IP")
    

    Needless to say, better avoid this latter one. If the array was initially sparse, the array indices will have changed after that assignment.

manatwork
  • 32.1k
  • 8
  • 104
  • 93