Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have written a small script that add particular IP addresses taken from a config file and then puts it in a list :

  WAS_IP=$(grep "<was_ip>" $CONFIG| cut -d '>' -f 2 | cut -d '<' -f 1 | xargs)

  NODES=()
  NODES+=("$WAS_IP")

On bash 3.2.25this works fine but on 3.0 where I have my production environment this gives an error :

./config.sh: line 3154: syntax error near unexpected token `"$WAS_IP"'
./config.sh: line 3154: `      NODES+=("$WAS_IP")'

How can I avoid this issue ?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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.

share|improve this answer
    
Very good answer. Thanks a lot @manatwork –  Patryk Feb 11 '13 at 14:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.