Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
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

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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