Bash

函式中聲明的 Bash 數組在函式外不可用

  • June 12, 2014

在 bash (v4.3.11) 終端上輸入:

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

(以下相同,只是為了在這裡更容易閱讀)

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

將輸出這個(在函式之外,數組失去了它的值,為什麼?)

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

我期待它輸出這個:

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

如何使它工作?

手冊頁

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

例子:

$ 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" )'

引用自:https://unix.stackexchange.com/questions/136720