From b1ef0a7e53d5b1332b6cb0888abb287977231104 Mon Sep 17 00:00:00 2001 From: daryl Date: Mon, 25 Jul 2022 15:55:22 +0930 Subject: [PATCH] Add ordering to associative array using an indexed array with matching values. --- bash/associative_array.bash | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bash/associative_array.bash b/bash/associative_array.bash index e4ce184..816ec23 100644 --- a/bash/associative_array.bash +++ b/bash/associative_array.bash @@ -25,3 +25,17 @@ done # key: repo_two # repo_one is true # key: repo_three + +# NOTE: Be care of -A versus -a in the array declaration. A -a makes an *indexed* array as opposed to an *associative* array. +# But given that an associative array is actually a hash table, it doesn't store the pairs in the order you put them +# into the array, they are instead stored in their hash value order. If order matters you need to use an indexed array. +# The following shows how to use both an indexed array and an associative array together to get both, if that's what you need. +# (Ref https://stackoverflow.com/questions/29161323/how-to-keep-associative-array-order) +declare -a arrOrder ; declare -A arrData +arrOrder+=( repo_one ) ; arrData[repo_one]=true +arrOrder+=( repo_two ) ; arrData[repo_two]=true +arrOrder+=( repo_three ) ; arrData[repo_three]=false +for i in "${arrOrder[@]}" +do + echo "$i: ${arrData[$i]}" +done