简体   繁体   中英

Ordered associative arrays in bash

I can do the following in bash :

declare -A data
data[A]="aaa"
data[C]="ccc"
data[B]="bbb"

for i in "${!data[@]}" ; do
    printf "%-20s ---> %s\n" "$i" "${data[$i]}"
done

Which outputs:

A                    ---> aaa
B                    ---> bbb
C                    ---> ccc

That is, the associative array is reordered (I assume using lexicographic ordering on the keys, but I am not sure), and loses the original order in which I created the data. I wanted instead:

A                    ---> aaa
C                    ---> ccc
B                    ---> bbb

In python I would use an OrderedDict instead of a plain dict for that. Is there a similar concept in bash?

As already answered, associative arrays are not ordered. If you want ordering in that array, use below work-around.

declare -A data
data_indices=()
data[A]="aaa"; data_indices+=(A)
data[C]="ccc"; data_indices+=(C)
data[B]="bbb"; data_indices+=(B)

for i in "${data_indices[@]}" ; do
    printf "%-20s ---> %s\n" "$i" "${data[$i]}"
done

There is no defined ordering of associative arrays in Bash. The ordering of output from your script will therefore be unpredictable. If you want to store more information in your array, I would suggest to create another parallel associative array that would use same keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM