[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Behaviour of test -v with assoc array and quote character in key

From: Chet Ramey
Subject: Re: Behaviour of test -v with assoc array and quote character in key
Date: Mon, 15 Feb 2021 09:11:48 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Thunderbird/78.7.1

On 2/14/21 6:27 PM, Daniel Gröber wrote:
Hi list,

I've found what I belive to be a bug in how `test -v` expands the key in an
associative array. The following minimal test case demonstrates the

     declare -A array
mytest () {
             test -v array["$1"]
             printf 'test -v array[%s]; $?=%s\n' "$1" "$?"
mytest 'a' # prints: test -v array[a]; $?=0
     mytest '"' # prints: test -v array["]; $?=1
     echo "keys: ${!array[*]}" # prints: keys: " a

With a regular alphanumeric key `test -v` will return zero, indicating the
array element exists. However if we specify a variable that expands to
something containing the double quote character the test doesn't succeeed
indicating the key doesn't exist though it does as we can observe by the
expansion of ${!array[*]}.

Do you think this intended behaviour or a real bug?

`test' is always going to be problematic here because, as a shell builtin,
its arguments undergo a round of word expansions before it's invoked. It's
difficult to reliably detect the closing bracket in an array subscript as a
result, even if the array subscript expansion didn't perform any expansions
on its own. (Consider what would happen if $1 were `]').

There are workarounds you can use to avoid the problem, involving adding a
set of quotes to suppress the expansion the array subscript evaluation

``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/

reply via email to

[Prev in Thread] Current Thread [Next in Thread]