在 Bash 中遍历多个数组时关联数组键中的空格

Spaces in Associative Array Keys while looping through multiple arrays in Bash

我在 bash 中遍历多个关联数组时遇到了一些麻烦。

这是我正在 运行ning 的代码:(删除了实际信息)

arrays=("arrayone" "arraytwo")
declare -A arrayone=(["one"]=1 ["two"]=2)
declare -A arraytwo=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
for array in ${arrays[*]} 
 do 
 for key in $(eval echo $\{'!'$array[@]\})   
       do 
       echo "$key"
       done
 done

在我 运行 进入其中有空格的键值之前,这工作得很好。无论我做什么,我都无法正确处理带空格的项目。

如果您有任何关于如何让它工作的想法,我将不胜感激。 如果有更好的方法来做到这一点,我很乐意听到。我不介意擦掉这个然后重新开始。这是迄今为止我能想到的最好的。

谢谢!

Bash 在 4.3 中添加了 nameref attribute。它允许您将一个名称专门作为对另一个名称的引用。在你的情况下,你会做

declare -A assoc_one=(["one"]=1 ["two"]=2)
declare -A assoc_two=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
declare -n array # Make it a nameref
for array in "${!assoc_@}"; do 
    for key in "${!array[@]}"; do
        echo "'$key'"
    done
done

你得到

'one'
'two'
'text with spaces'
'more text with spaces'

名称已更改以保护成语。我的意思是,我更改了数组名称,这样我就可以在不使 array 成为特例的情况下执行 "${!assoc_@}"