0

I am trying to access the last element of a bash associative array using the below code: # Declare an associative array declare -A myAssocArray

# Add key-value pairs to the associative array
myAssocArray["name"]="John"
myAssocArray["age"]=30
myAssocArray["city"]="New York"
myAssocArray["country"]="USA"

keys=("${!myAssocArray[@]}")  # Get all keys
last_key="${keys[-1]}"        # Access the last key
last_element="${myAssocArray[$last_key]}"  # Access the last elemen
echo "$last_element"

it outputs: john instead of USA actually I am trying to seek if any method is available like negative indices for last element access in assoc. arrays

4
  • 6
    The keys in an associative array are not ordered. There is no concept of "first" and "last". They are delivered in essentially random order. Commented Sep 27, 2023 at 6:19
  • 2
    So don't use associative array, but simple array with numeric keys Commented Sep 27, 2023 at 6:19
  • Thank you all for assistance. I understand the issue now Commented Sep 27, 2023 at 6:22
  • 1
    in some situations, you could maintain a helper indexed array - whenever you insert a hash key for the first time, append the key as a value in the helper. Then you can access the "last" element of the hash (the one most recently added) by dereferencing through the helper. eg: ${hash["${helper[-1]}"]} Commented Sep 27, 2023 at 17:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.