How to access the last element of a bash associative array?

68 Views Asked by At

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

0

There are 0 best solutions below