Associative arrays are local by default

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

    For those who are stuck with Bash version < 4.2 and are not comfortable with proposed workarounds I share my custom implementation of global associative arrays. It does not have the full power of bash associative arrays and you need to be careful about special characters in array index, but gets job done.

    get_array(){
       local arr_name="$1"
       local arr_key="$2"
    
       arr_namekey_var="ASSOCARRAY__${arr_name}__${arr_key}"
       echo "${!arr_namekey_var:=}"
    }
    
    set_array(){
       local arr_name="$1"
       local arr_key="$2"
       local arr_value="$3"
    
       arr_namekey_var="ASSOCARRAY__${arr_name}__${arr_key}"
       if [[ -z "${arr_value}" ]]; then
          eval ${arr_namekey_var}=
       else
          printf -v "${arr_namekey_var}" "${arr_value}"
       fi
    }
    

    Few notes:

    • Array name and array key could be combined into a single value, but split proved convenient in practice.
    • __ as a separator can by hacked by malicious or careless use -- to be on the safe side use only single-underscore values in array name and key, on top of only using alphanumeric values. Of course the composition of the internal variable (separators, prefix, suffix...) can be adjusted to application and developer needs.
    • The default value expansion guarantees that undefined array key (and also array name!) will expand to null string.
    • Once you move to version of bash where you are comfortable with builtin associative arrays, these two procedures can be used as wrappers for actual associative arrays without having to refactor whole code base.

提交回复
热议问题