How to keep associative array order?

后端 未结 3 612
抹茶落季
抹茶落季 2020-12-05 02:32

I try to iterate over an associative array in Bash.

It seems to be simple, but the loop doesn\'t follow the initial order of the array.

Here is a simple scri

3条回答
  •  盖世英雄少女心
    2020-12-05 03:30

    Another way to sort entries in your associative array is to keep a list of the groups as you add them as an entry in the associative array. Call this entry key "group_list". As you add each new group, append it to the group_list field, adding a blank space to separate subsequent additions. Here's one I did for an associative array I called master_array:

    master_array["group_list"]+="${new_group}";
    

    To sequence through the groups in the order you added them, sequence through the group_list field in a for loop, then you can access the group fields in the associative array. Here's a code snippet for one I wrote for master_array:

    for group in ${master_array["group_list"]}; do
        echo "${group}";
        echo "${master_array[${group},destination_directory]}";
    done
    

    and here's the output from that code:

    "linux"
    "${HOME}/Backup/home4"
    "data"
    "${HOME}/Backup/home4/data"
    "pictures"
    "${HOME}/Backup/home4/pictures"
    "pictures-archive"
    "${HOME}/Backup/home4/pictures-archive"
    "music"
    "${HOME}/Backup/home4/music"
    

    This is similar to the suggestion by Jonathan Leffler, but keeps the data with the associative array rather than needing to keep two separate disjoint arrays. As you can see, it's not in random order, nor in alphabetical order, but the order in which I added them to the array.

    Also, if you have subgroups, you can create subgroup lists for each group, and sequence through those as well. That's the reason I did it this way, to alleviate the need for multiple arrays to access the associative array, and also to allow for expansion to new subgroups without having to modify the code.

    EDIT: fixed a few typos

提交回复
热议问题