Search code examples
bashassociative-array

Bash: Access associateive array using for loop variables does not work


I am currently trying to create a whiptail menu to get a key for the associative array and then using a for loop to access the data in the associative array.

This is the bash code I am using:

#!/bin/bash

declare -A backup_source=( [HDD]="Samsung/WD" [Monitor]="/LG/DELL" )


set -x

myArray=()

for key in "${!backup_source[@]}"
do

        myArray+=("$key" "Backup ${backup_source[$key]} to ${backup_destination[$key]}" OFF)

done

BACKUP_CHOICES=( $(whiptail --title "TEST" --checklist "This is just a test" 20 100 10 "${myArray[@]}" 3>&1 1>&2 2>&3) )
#echo "$BACKUP_CHOICES"

for mychoice in "${BACKUP_CHOICES[@]}"
do

        echo $mychoice
        echo ${backup_source[$mychoice]}

done

However, the output is:

+ backup_source=(['HDD']='Samsung/WD' ['Monitor']='/LG/DELL')
+ declare -A backup_source
+ set -x
+ myArray=()
+ for key in "${!backup_source[@]}"
+ myArray+=("$key" "Backup ${backup_source[$key]} to ${backup_destination[$key]}" OFF)
+ for key in "${!backup_source[@]}"
+ myArray+=("$key" "Backup ${backup_source[$key]} to ${backup_destination[$key]}" OFF)
+ BACKUP_CHOICES=($(whiptail --title "TEST" --checklist "This is just a test" 20 100 10 "${myArray[@]}" 3>&1 1>&2 2>&3))
++ whiptail --title TEST --checklist 'This is just a test' 20 100 10 Monitor 'Backup /LG/DELL to ' OFF HDD 'Backup Samsung/WD to ' OFF
+ for mychoice in "${BACKUP_CHOICES[@]}"
+ echo '"Monitor"'
"Monitor"
+ echo

The echo ${backup_source[$mychoice]} is empty.

Expected output would be

"/LG/DELL"

The funny thing is if I define the variable $mychoice in the for loop explictly like mychoice="Monitor" then it works.

Anyone knows what I am doing wrong?


Solution

  • Thanks to joanis, the problems were the double quotes as a result of the whiptail return. this code works now:

    #!/bin/bash
    
    declare -A backup_source=( [HDD]="Samsung/WD" [Monitor]="/LG/DELL" )
    
    
    set -x
    
    myArray=()
    
    for key in "${!backup_source[@]}"
    do
    
            myArray+=("$key" "Backup ${backup_source[$key]} to ${backup_destination[$key]}" OFF)
    
    done
    
    BACKUP_CHOICES=( $(whiptail --title "TEST" --checklist "This is just a test" 20 100 10 "${myArray[@]}" 3>&1 1>&2 2>&3) )
    echo "${BACKUP_CHOICES[@]}"
    
    for mychoice in "${BACKUP_CHOICES[@]}"
    do
    
            echo $mychoice
            mychoice="${mychoice%\"}"; mychoice="${mychoice#\"}"
            echo "${backup_source[$mychoice]}"
    
    done