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.
declare -- a=""
as output for the firstdeclare -p
above (RedHat, bash 3.2.25(1)-release.