4

on bash (v4.3.11) terminal type this:

function FUNCtst() { declare -A astr; astr=([a]="1k" [b]="2k" ); declare -p astr; };FUNCtst;declare -p astr

(same thing below, just to be easier to read here)

function FUNCtst() { 
  declare -A astr; 
  astr=([a]="1k" [b]="2k" ); 
  declare -p astr; 
};
FUNCtst;
declare -p astr

will output this (outside of the function the array looses its value, why?)

declare -A astr='([a]="1k" [b]="2k" )'
bash: declare: astr: not found

I was expecting it output this:

declare -A astr='([a]="1k" [b]="2k" )'
declare -A astr='([a]="1k" [b]="2k" )'

how to make it work?

1 Answer 1

12

From the man page:

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

Example:

FUNCtst() { 
    declare -gA astr
    astr=([a]="1k" [b]="2k" )
    declare -p astr
}
FUNCtst
declare -p astr

prints

declare -A astr=([a]="1k" [b]="2k" )
declare -A astr=([a]="1k" [b]="2k" )

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.