Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Inconsistent behavior of the test command with associative arrays



This doesn't have anything to do with associative arrays and everything to do with "test" and quoting.

On Wed, Apr 17, 2024 at 2:37 PM limited time <burnermail4now@xxxxxxxxx> wrote:
% zsh -f
% typeset -A array=(key1 value1 key2 value2);
test $array[key1] ; echo $? ;
test $array[key2] ; echo $? ;

These two are "test somestring" which is defined as true.
 
test $array[key3] ; echo $? ;
test $array[key4] ; echo $? ;

These two are just "test" (with no arguments at all, because key3 and key4 have no value) which is defined as false.
 
if test $array[key1] -a $array[key2] ; then
  echo "Condition evaluated to true" ;
fi            

This is "test string -a string" which is true because neither string is empty.
 
if test $array[key3] -a $array[key4] ; then             
  echo "Condition evaluated to true" ;
fi

This is "test -a" because both expansions are empty and not quoted so they disappear from the command line entirely.

By definition, "test -a" is treated as "test somestring" and is true.


Messages sorted by: Reverse Date, Date, Thread, Author