Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

From man page:

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

Example:

$ function FUNCtst() { declare -gA astr; astr=([a]="1k" [b]="2k" ); declare -p astr; };FUNCtst;declare -p astr
declare -A astr='([a]="1k" [b]="2k" )'
declare -A astr='([a]="1k" [b]="2k" )'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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