Skip to content
Advertisement

Adding value to an associative array named after a variable

I need your help with a bash >= 4 script I’m writing.

I am retrieving some files from remote hosts to back them up. I have a for loop that iterate through the hosts and for each one tests connection and the start a function that retrieves the various files.

My problem is that I need to know what gone wrong (and if), so I am trying to store OK or KO values in an array and parse it later.

This is the code:

...
for remote_host in $hosts ; do
    short_host=$(echo "$remote_host" | grep -o '^[^.]+')
    declare -A cluster
    printf "INFO: Testing connectivity to %s...   " "$remote_host"
    if ssh -q "$remote_host" exit ; then
        printf "OK!n"
        cluster[$short_host]="Reacheable"
        mkdir "$short_host"
        echo "INFO: Collecting files ..." 
        declare -A ${short_host}
        objects1="/etc/krb5.conf /etc/passwd /etc/group /etc/fstab /etc/sudoers /etc/shadow"
        for obj in ${objects1} ; do
            if file_retrieve "$user" "$remote_host" "$obj" ; then
->              ${short_host}=["$obj"]=OK
            else
                ${short_host}=["$obj"]=KO

            fi
        done
...

So I’m using an array named cluster to list if the nodes were reacheable, and another array – named after the short name of the node – to list OK or KO for single files. On execution, I got the following error (line 130 is the line I marked with the arrow above):

./test.sh: line 130: ubuntu01=[/etc/krb5.conf]=OK: command not found

I think this is a synthax error for sure, but I can’t fix it. I tried a bunch of combinations without success.

Thanks for your help.

Advertisement

Answer

Since the array name is contained in a variable short_list, you need eval to make the assignment work:

${short_host}=["$obj"]=OK

Change it to:

eval ${short_host}=["$obj"]=OK
eval ${short_host}=["$obj"]=OK

Similar posts:

Single line while loop updating array

Advertisement