0

I'm using Ubuntu terminal installed over Window 10. I create ASSOCIATIVE ARRAY VARIABLE and access in using INDEX using BASH in Ubuntu.

### 84) Create an ARRAY VARIABLE Accessed By Value

    declare -A car
    car[BMW]=i8
    car[TOYOTA]=Corolla
    car[Honda]=Civic
    car[Mercedes]=Benz

    echo "${car[TOYOTA]}"

It should return 'Corolla'. But instead it returns: 'Benz'

output

2
  • 1
    Use -A not -a, see help declare and arrays Commented Nov 3, 2021 at 20:58
  • Your code works correctly. Please run your code in a fresh terminal. Commented Nov 4, 2021 at 1:49

1 Answer 1

2

declare -a creates a numerically indexed array.
declare -A creates an associative array.

Numerically indexed arrays place the index part of var[idx]=value into an arithmetic context. In an arithmetic context, variables can be used without the "parameter expansion syntax" (i.e. the $). Unset variables use the value zero.

So, what you're doing with

declare -a car # '-a' used to let this variable have assigned values below
car[BMW]=i8
car[TOYOTA]=Corolla
car[Honda]=Civic
car[Mercedes]=Benz

is assigning each value to the index zero of the array.

declare -p is a handy way to inspect a variable:

$ declare -p car
declare -a car=([0]="Benz")

with declare -A instead, we get:

$ declare -p car
declare -A car=([Honda]="Civic" [TOYOTA]="Corolla" [BMW]="i8" [Mercedes]="Benz" )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Glenn Jackman. Though I watched a video with the same code I posted above (except for '-A', which was a typo on my side.) So, the guy in the tutorial it returned 'Corolla'.

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.