这是我的功能,我在读取文件,按空格分配每一行并创建一个数组。我想将数组中的第一和第二个元素用作关键和值。第一个元素是IP地址。
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"
}
问题&amp;调查结果:
* declare -A doesn't work, using `GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)`
./test.sh:第4行:声明:-a:无效选项声明:用法:声明[-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:第14:127.0.0.1:语法错误:无效算术操作员(错误令牌为" .0.0.1")
This is line 14: HOSTS_IP_ARR["$HOST_IP"]="${HOST_AZ}"
declare -A doesn't work, using `GNU bash, version **3.2.25(1)-release** (x86_64-redhat-linux-gnu)`
有您的问题。关联阵列仅在版本4中引入Bash。
declare -a
创建一个常规的非求解数组。
它似乎是关联的:
declare -a arr
arr["somekey"]=42
echo "${arr["somekey"]}" # gives 42
但是
arr["someotherkey"]=1000
echo "${arr["somekey"]}" # now gives 1000
这是因为"somekey"
和"someotherkey"
被解释为算术表达式。Bash试图将它们查找为可变名称,发现它们不设置,因此将值视为0
。
127.0.0.1
是无效的算术表达式,这就是为什么您会遇到错误的原因。