declare -A doesn't work, using `GNU bash, version **3.2.25(1)-release** (x86_64-redhat-linux-gnu)`
There's your problem. Associative arrays were only introduced into bash in version 4.
Question
This is my function where I'm reading a file, splitting each line by space and creating an array. I want to use 1st and 2nd element from the array as key and value to an associative array. The 1st element is an ip address.
function testRead {
NEWHOST_IPS_OUT=<my_file>
declare -a HOSTS_IP_ARR
while read line
do
if [[ -z "$line" ]] || [[ "$line" =~ "#" ]]; then
continue
fi
STR_ARRAY=($line)
HOST_IP=${STR_ARRAY[1]}
HOST_AZ=${STR_ARRAY[2]}
HOSTS_IP_ARR["$HOST_IP"]="${HOST_AZ}"
HOSTS_IP_ARR[hello]=2
done < "$NEWHOST_IPS_OUT"
}
Issues & Findings:
* declare -A doesn't work, using `GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)`
./test.sh: line 4: declare: -A: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
* I tested with constant values using '-a' for an associative array. It worked
* On running this script I get the following error:
./test.sh: line 14: 127.0.0.1: syntax error: invalid arithmetic operator (error token is ".0.0.1")
This is line 14: HOSTS_IP_ARR["$HOST_IP"]="${HOST_AZ}"
Solution
declare -A doesn't work, using `GNU bash, version **3.2.25(1)-release** (x86_64-redhat-linux-gnu)`
There's your problem. Associative arrays were only introduced into bash in version 4.
OTHER TIPS
declare -a
creates a regular, non-associative array.
It could appear to be associative:
declare -a arr
arr["somekey"]=42
echo "${arr["somekey"]}" # gives 42
but
arr["someotherkey"]=1000
echo "${arr["somekey"]}" # now gives 1000
This is because "somekey"
and "someotherkey"
are interpretted as arithmetic expressions. Bash tries to look them up as variable names, find them unset, and therefore consider the value to be 0
.
127.0.0.1
is an invalid arithmetic expression, and that's why you get that error.