Bash 4生成关联数组

时间:2016-07-20 17:56:22

标签: bash associative-array

我正在尝试从输出中创建一个漂亮的整洁表。这是现在正在使用的代码:

vmnumber=0
declare -A vm_array=()

for vm in $vms; do
    declare vm_array[$vmnumber][cpu]="10"
    echo "Test ${vm_array[$vmnumber][cpu]}"
    declare vm_array[$vmnumber][memory]="20"
    declare vm_array[$vmnumber][diskspace]="20"
    vmnumber=$(($vmnumber + 1))
done

# Table output
for((i=0;i<$vmnumber;i++)); do
    printf "%10s %10s %10s" vm_array[$i][cpu] vm_array[$i][memory] vm_array[$i][diskspace]"
done

Echo不起作用,只有变量名在printf中出现。

如何生成这些值中的关联数组?

1 个答案:

答案 0 :(得分:1)

关联数组支持非数字键。它们不是多维,并且不能将其他数组作为您的值。对于您的用例,请为每个VM使用单独的非关联数组,如下所示:

# Why this is this associative at all, if your keys are numeric?
vmnumber=0
vm_cpu=() vm_memory=() vm_diskspace=( )

for vm in $vms; do ## aside: don't use for this way
    vm_cpu[$vmnumber]="10"
    vm_memory[$vmnumber]="20"
    vm_diskspace[$vmnumber]="20"
    (( ++vmnumber ))
done

# test output
declare -p vm_cpu vm_memory vm_diskspace

# Table output
for i in "${!vm_cpu[@]}"; do # iterate over keys
    printf '%10s %10s %10s\n' "${vm_cpu[$i]}" "${vm_memory[$i]}" "${vm_diskspace[$i]}"
done

如果您真的想要一个关联数组,那将如下所示:

vmnumber=0
declare -A vm_data=( )

for vm in $vms; do ## aside: don't use for this way
    vm_data[cpu_$vmnumber]="10"
    vm_data[memory_$vmnumber]="20"
    vm_data[diskspace_$vmnumber]="20"
    (( ++vmnumber ))
done

# test output
declare -p vm_data

# Table output
for ((i=0; i<vmnumber; i++)); do
    printf '%10s %10s %10s\n' "${vm_data[cpu_$i]}" "${vm_data[memory_$i]}" "${vm_data[diskspace_$i]}"
done