bug-bash
[Top][All Lists]
Advanced

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

Re: test '-v' - associative vs. normal array discrepancy - a bug ?


From: Jason Vas Dias
Subject: Re: test '-v' - associative vs. normal array discrepancy - a bug ?
Date: Wed, 19 Nov 2014 19:59:42 +0000

Thanks to all who replied.

I would really like -v to do as it documented to do :
" -v
   True if the shell variable varname is set (has been assigned a value)
"
To me, the fact that -v does not return true if the variable is an array
and does not have element 0 - or element '0' in the case of assocs -
means it does not behave as documented.
Either its behaviour should be changed to return true if an array is
non-empty (contains ANY non-empty element) or the documentation should
be changed to document '-v's behaviour for both normal and associative
arrays.

This is the function I was using to replace -v if bash version < 4.3
is detected -
it does more than -v in that it actually returns the value of the variable,
but it works for any array or array member, and does not care if
the array does not have element 0 or member '0' :
function is_defined
{
   if (( $# == 0 )); then
      return 1;
   fi
   local v="$1";
   if [[ "$v" =~ \[ ]]; then
       local val;
       eval  'val="${'$v'}"';
       if [ x"$val" = x ]; then
          return 1;
       fi
       echo -n "${val//[\'\"]/}";
       return 0;
   else
       local val="$(declare -p $v 2>/dev/null)";
       if [[ "$val" =~ ^declare[\ \     xaAgri\-]+[\ \  ]*[^\ \
\=]+[\=]([^\=].*)[\ \   ]*$ ]]; then
           val="${BASH_REMATCH[1]/()/}";
       else
           return 1;
       fi
       echo -n "${val//[\'\"]/}";
  fi
}

I thought the intent of -v was to free us of such code .

I think there is a need for some built-in or test option
that can tell us if a variable has been set or not, regardless
if it is an array or if its 0th element or member '0' is set or not.
To get this currently, we'd have to test if the variable is an
array, if it is an associative or normal array, and have different
methods for each case .   [ address@hidden -gt 0 ] does not work
if $v is a  normal variable.

It would be nice if -v could mean 'has any non-empty member' for
both associative and normal arrays - I think Piotr's suggestion
to make it do this is a good one.

Thanks & Regards,
Jason



On 11/19/14, Piotr Grzybowski <address@hidden> wrote:
> On Wed, Nov 19, 2014 at 8:25 PM, Chet Ramey <address@hidden> wrote:
>>
>> No.  There's a way to test for a non-zero number of elements directly.
>>
>
>  Sure thing, I just had a feeling that Jason wants to use -v instead.
> I can turn it into
>
> -E VAR     True if the shell variable VAR is an empty array
>
> ;-)
>
> cheers,
> pg
>



reply via email to

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