3

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?

2
  • 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, 2012 at 21:19
  • I have reported this potential bug to [email protected].
    – Tim Friske
    Nov 26, 2012 at 21:49

1 Answer 1

4
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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .