Ken J
Ken J

Reputation: 4562

Bash 4 Generate Associative Array

I'm trying to create a nice neat table from output. Here's the code that working off of now:

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 is not working and only the variable names come out in printf.

How can I generate an associative array of out of these values?

Upvotes: 0

Views: 55

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295272

Associative arrays support non-numeric keys. They are not multidimensional, and cannot have other arrays as your values. For your use case, use a separate non-associative array per VM, as follows:

# 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

If you really want a single associative array, that would look like the following:

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

Upvotes: 1

Related Questions