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")
Run Code Online (Sandbox Code Playgroud)
On bash 3.2.25
this 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")'
Run Code Online (Sandbox Code Playgroud)
How can I avoid this issue ?
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"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
Needless to say, better avoid this latter one. If the array was initially sparse, the array indices will have changed after that assignment.
归档时间: |
|
查看次数: |
863 次 |
最近记录: |