3

When I execute the following code in Bash version "GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)", I get:

declare a
declare -p a
# Output: -bash: declare: a: not found
declare -i b
declare -p b
# Output: -bash: declare: b: not found
declare -a c
declare -p c
# Output: declare -a c='()'
declare -A d
declare -p d
# Output: declare -A d='()'

Arguably I think that the above variables should either be initialized in all cases or in none of them. That would seem more consistent rather than initializing only arrays upon declaration.

3
  • What version of bash do you have? I'm getting declare -- a="" as output for the first declare -p above (RedHat, bash 3.2.25(1)-release.
    – Mat
    Nov 27, 2012 at 12:18
  • I've written a mail to [email protected] and got the following answer from [email protected], presumably the maintainer of the Bash shell: "Thanks for the report. This is an artifact of how the arrays/hash tables are initialized by `declare', as you suspect. The variable should remain undefined until explicitly assigned a value. I will take a look and see what effect that will have on other parts of the code."
    – Tim Friske
    Nov 27, 2012 at 22:56
  • Yes, Chet Ramey is the longtime Bash shell maintainer.
    – fpmurphy
    Dec 27, 2012 at 22:48

1 Answer 1

1

I presume one could always safely and uniformly declare and initialize variables as follows:

declare a=""
declare -p a
# Output: declare -- a=""
declare -i b=0
declare -p b
# Output: declare -i b="0"
declare -a c=()
declare -p c
# Output: declare -a c='()'
declare -A d=()
declare -p d
# Output: declare -A d='()'

Given that there seems to be differing behavior accross different releases of the Bash shell.

When one doesn't provide an explicit initialization value while declaring a variable the result might not what one expects as demonstrated in the following example with local variables:

function foobar {
  declare a
  declare -i b
  declare -a c
  declare -A d
  declare -p a b c d
  a=a
  b=42
  c+=(c)
  d+=([d]=42)
  declare -p a b c d
}
foobar
# Output:
# declare -- a=""
# declare -i b=""
# declare -a c='()'
# declare -A d='()'
# Output:
# declare -- a="a"
# declare -i b="42"
# declare -a c='([0]="c")'
# declare -A d='([d]="42" )'
declare -p a b c d
# Output:
# bash: declare: a: not found
# bash: declare: b: not found
# bash: declare: c: not found
# bash: declare: d: not found

In the case of local variables and late initialization everything works as expected. Particularly note that the first declare -p a b c d inside the foobar function reports all variables as being initialized to their data type specific default values. Compare that to the global variable case where the a and b variables were reported as -bash: declare: a: not found and -bash: declare: b: not found, respectively.

You must log in to answer this question.

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