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
problem:
declare -A array
mytest () {
array["$1"]=123
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
performs.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU c...@case.edu http://tiswww.cwru.edu/~chet/