Skip to main content
edited tags
Link
Gilles 'SO- stop being evil'
  • 865.5k
  • 205
  • 1.8k
  • 2.3k
Source Link

Ordered by insertion Map in bash

Is there an ordered (by insertion) map in bash?

I know there's an associative array data structure in bash, but when iterating over it, the order of the elements is not by insertion. Example below.

I'd like to keep the map ordered by insertion.

Associative array not preserving insertion order:

declare -A REPLACE_MAP
REPLACE_MAP['b']='2'
REPLACE_MAP['a']='1'
for key in "${!REPLACE_MAP[@]}"; do
    echo "$key - ${REPLACE_MAP["$key"]}"
    value=${REPLACE_MAP["$key"]}
done

Result:

a - 1
b - 2

I'd like a data structure that will yield the following result:

b - 2
a - 1