I execute the following code in Bash version "GNU bash, Version 4.2.39(1)-release (x86_64-redhat-linux-gnu)":

function foobar {
  declare -rgA FOOBAR=([foo]=bar)
}
foobar
declare -p FOOBAR
# Output: declare -Ar FOOBAR='()'

Why doesn't Bash initialize FOOBAR with ([foo]=bar) according to declare -p? The same declaration works outside of a function, e.g.

declare -rgA FOOBAR=([foo]=bar)
declare -p FOOBAR
# Output: declare -Ar FOOBAR='([foo]="bar" )'

Similarly the following code but without FOOBAR being read-only works:

function foobar {
  declare -gA FOOBAR
  FOOBAR=([foo]=bar)
}
foobar
declare -p FOOBAR
# Output: declare -A FOOBAR='([foo]="bar" )'

Is this a bug or feature?

  • Looks like a bug to me. I would use bashbug to send it off the mailing list. -g for declare is new in 4.2, so I wouldn't be surprised if this case was missed in testing. – jordanm Nov 26 '12 at 21:19
  • I have reported this potential bug to bug-bash@gnu.org. – Tim Friske Nov 26 '12 at 21:49
function foobar {
  declare -rgA 'FOOBAR=([foo]=bar)'
}
foobar
declare -p FOOBAR

(note the extra quotes) works for me.

You'll even find that in:

function foobar {
  var="something tricker"
  declare -rgA 'FOOBAR=([foo]=$var)'
}
foobar
declare -p FOOBAR

$var is expanded even if it's quoted.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.