3

The test case is as follows:

sourced-file.sh:

#!/bin/bash

declare -A MY_MAP=();

function C_function() {
  MY_MAP[foo]="bar";
}
  1. First test

test.sh

#!/bin/bash

function A_function() {
  source sourced-file.sh
  B_function;
  declare -p MY_MAP;
}    
function B_function() {
  C_function;
  declare -p MY_MAP;
}
A_function;

Running ./test.sh prints:

declare -A MY_MAP=([foo]="bar" )
declare -A MY_MAP=([foo]="bar" )
  1. Second test

test.sh

#!/bin/bash

function A_function() {
  source sourced-file.sh
  B_function;
  declare -p MY_MAP;
}    
function B_function() {
  source sourced-file.sh
  C_function;
  declare -p MY_MAP;
}
A_function;

Running ./test.sh now prints:

declare -A MY_MAP=([foo]="bar" )
declare -A MY_MAP=()
  1. third test

test.sh

#!/bin/bash

function A_function() {
  B_function;
  declare -p MY_MAP;
}    
function B_function() {
  source sourced-file.sh
  C_function;
  declare -p MY_MAP;
}
A_function;

Running ./test.sh now prints:

declare -A MY_MAP=([foo]="bar" )
./test.sh: line 5: declare: MY_MAP: not found

I'm using bash 4.4.23, and I'd like to understand this behavior. Could someone shed light on this?

2 Answers 2

2

When used inside a function without -g, declare declares a local variable. Sourcing declare from a function works the same way, i.e. it creates a local variable. Adding -g would not empty the array in case 2 and would recognise the array in case 3.

0
2

When used in a function, declare makes each name local, as with the local command, unless the -g option is used.

When you source within a function, the declared variables are local to that function (and visible in functions/subshells that you invoke from that function).

a demo:

a() { local x=10; echo "a before: $x"; b; echo "a after: $x"; }
b() { local x=20; echo "b before $x"; c; echo "b after: $x"; }
c() { echo "c before: $x"; x=30; echo "c after: $x"; }
x=5
a
echo $x

outputs

a before: 10
b before 20
c before: 20
c after: 30
b after: 30
a after: 10
5

Without testing it, if you declare -gA MY_MAP in the sourced filed, I expect you'll have different results.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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