Bad array subscript error when trying to increment an associative array element

前端 未结 2 1635
一向
一向 2020-12-11 05:19

I can create an associative array and assign an integer to a key that contains a single quote in it:



        
2条回答
  •  暖寄归人
    2020-12-11 06:07

    Turn off multiple evaluation* of associative array subscripts with following command and it'll work.

    shopt -s assoc_expand_once
    

    * An example showing the default behavior and assoc_expand_once's effect:

    $ v1=42
    $ v2='$v1'
    $ declare -A foo
    $ foo[$v2]=
    $ declare -p foo
    declare -A foo=(["\$v1"]="" )
    $ (( foo[$v2]++ ))
    $ declare -p foo
    declare -A foo=([42]="1" ["\$v1"]="" )
    $
    $ shopt -s assoc_expand_once
    $ (( foo[$v2]++ ))
    $ declare -p foo
    declare -A foo=([42]="1" ["\$v1"]="1" )
    

提交回复
热议问题