2

Every example I have found tends to go aa["key"]="value" and even with constants, e.g.:

declare -rA aa=( ["lit1"]="value1" ["lit2"]="value2" )

What is the purpose of this, i.e. does it guard against something I am not foreseeing with literals? The purpose is obvious to me when something is about to be expanded within the quotes, but with constants the code then starts to look less, not more readable.

I checked the two best resources I can think of, the reference and Greg's wiki. It's not explicitly covered anywhere, the former conflates it with regular arrays where it was a non-issue.

2
  • shellcheck accepts both echo -e '#!/bin/bash\n declare -rA aa=( [lit1]="value1" [lit2]="value2" ); echo "${aa[@]}"' | shellcheck -. No errors or warnings. Commented Jun 14 at 21:23
  • @LMC I use shellcheck too, but sometimes it's not about what's in there right at hand, but what it could become. Here, however, I tested with keys being literals identical to words like shift or even a pipe | symbol and it worked fine. It's almost like anything inside [ ] is safe as if it were in quotes already. Even declare -A A=( [$(echo a) $(echo b)]=1 ) appears safe. Commented Jun 14 at 21:31

1 Answer 1

4

Downside of NOT using quotes for keys of associative array?

No downside.

What is the purpose of this,

The purpose is to visually represent what is a string and what is a command, and to differentiate between associative and non-associative array. It's cosmetics.

does it guard against something I am not foreseeing with literals?

No.

Sign up to request clarification or add additional context in comments.

2 Comments

IMO the cosmetic effect of quotes is very important. If I see something like ${arr[x]} or arr[x]=..., my first thought is that x is a variable that'll be evaluated to an integer to index into a normal (numeric-indexed) array. ${arr["x"]} and arr["x"]=... make it immediately clear that these are string indexes into an associative array. So bash doesn't need the quotes to figure out what's going on, but I do.
@GordonDavisson This would be an issue for me if shell did not have the $ notation, but given how it is used in parameter expansion where it is completely normal to say var=${1:-default}, I got used to it so much it does not even bother me when function name is the "same" as variable. Also, it's impractical when you create constant associative arrays. Now that I know the [ ] are as safe as " " I am definitively omitting it everywhere.

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.