Associative arrays are local by default

后端 未结 5 1679
故里飘歌
故里飘歌 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:13

    This example declares a global associative array variable inside a function, in bash.

    set -euf +x -o pipefail # There is no place for implicit errors in this script.
    
    function init_arrays(){
        # FYI. Multiple array declarations are not a problem. You can invoke it multiple times.
    
        # The "-gA" switch is the trick for the global array declaration inside a function.
        declare -gA my_var
    }
    
    function do_work(){
        init_arrays
    
        my_var[$1]=OPPA
    }
    
    do_work aa
    
    echo ${my_var[aa]}
    echo It is expected to get OPPA value printed above
    

    Tested on GNU bash, version 4.4...

    Important notes.
    The declare -A command doesn't actually create an associative array immediately; it just sets an attribute on a variable name which allows you to assign to the name as an associative array. The array itself doesn't exist until the first assignment (!!!).

    (I wanted to see a complete working example in this thread, sorry.)

提交回复
热议问题