Consider the following bash script:
#!/usr/bin/env /bin/bash
function sourcefile(){
source /tmp/srcfile
echo "Sourced array in func: ${sourcedarray[*]}"
echo "Sourced scalar in func: ${sourcedscalar}"
}
globalarray=([0]="xyzzy" [1]="kaboom")
globalscalar="argle"
cat >/tmp/srcfile <<EOF
export sourcedscalar="bargle"
export sourcedarray=([0]="foo" [1]="bar")
EOF
sourcefile
echo "Global array: ${globalarray[*]}"
echo "Global scalar: ${globalscalar}"
echo "Sourced array: ${sourcedarray[*]}"
echo "Sourced scalar: ${sourcedscalar}"
One would reasonably expect all four values to be set in the output, but at least with bash version 3.2.57(1)-release (yes, yes I know: we all pay for Apple's paranoia) that is not the case:
Sourced array in func: foo bar
Sourced scalar in func: bargle
Global array: xyzzy kaboom
Global scalar: argle
Sourced array:
Sourced scalar: bargle
As far as I can tell:
- a scalar variable created in a function by sourcing a file is created in global scope
- but an array variable created in a function by sourcing a file is created in local scope, and exporting it does not change this
This seems inconsistent to put it mildly: is there some way to work around this behavior?