Associative arrays are local by default

后端 未结 5 1681
故里飘歌
故里飘歌 2021-02-01 14:50

Associative arrays seem to be local by default when declared inside a function body, where they should be global. The following code

#!/bin/bash

f() {
    decla         


        
5条回答
  •  借酒劲吻你
    2021-02-01 15:03

    Fine, 4.2 adds "declare -g" but it's buggy for associative arrays so it doesn't (yet) answer the question. Here's my bug report and Chet's confirmation that there's a fix scheduled for the next release.

    http://lists.gnu.org/archive/html/bug-bash/2013-09/msg00025.html

    But I've serendipitously found a workaround, instead of declaring the array and assigning an initial value to it at the same time, first declare the array and then do the assignment. That is, don't do this:

    declare -gA a=([x]=1 [y]=2)
    

    but this instead:

    declare -gA a; a=([x]=1 [y]=2)
    

提交回复
热议问题