我正在尝试创建一个多维关联数组,但需要一些帮助.我已经回顾了
the page suggested in this SO answer,但更让我感到困惑.到目前为止这里是我所拥有的:
剧本:
#!/bin/bash declare -A PERSONS declare -A PERSON PERSON["FNAME"]='John' PERSON["LNAME"]='Andrew' PERSONS["1"]=${PERSON[@]} PERSON["FNAME"]='Elen' PERSON["LNAME"]='Murray' PERSONS["2"]=${PERSON[@]} for KEY in "${!PERSONS[@]}"; do TMP="${PERSONS["$KEY"]}" echo "$KEY - $TMP" echo "${TMP["FNAME"]}" echo "${TMP["LNAME"]}" done
输出:
1 - John Andrew John Andrew John Andrew 2 - Elen Murray Elen Murray Elen Murray
正如你所看到的,试图访问for循环中的$TMP数组的特定索引返回整个数组.
[Q]为了单独访问for循环中$TMP数组的“FNAME”和“LNAME”索引,我需要做些什么?
谢谢.
你不能做你想做的事情:
bash arrays是一维的
原文链接:https://www.f2er.com/bash/386026.html$declare -A PERSONS $declare -A PERSON $PERSON["FNAME"]='John' $PERSON["LNAME"]='Andrew' $declare -p PERSON declare -A PERSON='([FNAME]="John" [LNAME]="Andrew" )' $PERSONS[1]=([FNAME]="John" [LNAME]="Andrew" ) bash: PERSONS[1]: cannot assign list to array member
您可以通过组合一个合适的数组索引字符串来伪造多维度:
declare -A PERSONS declare -A PERSON PERSON["FNAME"]='John' PERSON["LNAME"]='Andrew' i=1 for key in "${!PERSON[@]}"; do PERSONS[$i,$key]=${PERSON[$key]} done PERSON["FNAME"]='Elen' PERSON["LNAME"]='Murray' ((i++)) for key in "${!PERSON[@]}"; do PERSONS[$i,$key]=${PERSON[$key]} done declare -p PERSONS # ==> declare -A PERSONS='([1,LNAME]="Andrew" [2,FNAME]="Elen" [1,FNAME]="John" [2,LNAME]="Murray" )'