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

Re: Bitwise ops in a conditional



In the last episode (Apr 06), djh  said:
> This should be fairly simple, but I missed something.
> 
> I want to test if a shell variable is odd or not in a conditional to
> generate a simple odd/even testing which seems natural to me.
> 
> I did the below:
> 
> 	  if [[ ((index & 0x01)) .eq 1 ]]  then
> 	    print "odd index processing"
> 	  else
> 	    print "even index processing
> 	  fi
> 
> Actually I thought that a simple
>
>  if [[ index & 0x01 ]] should work, but conditionaly
>  may requie 2 args?

The if statement doesn't require a conditional expression; all it wants
is something that returns 0 or nonzero.  Use an arithmetic expression
directly (which returns 1 if the expression evaluates to zero, and 0
otherwise, to adhere to the shell's idea of "true is 0, false is 1"):

if (( index & 0x01 )) ; then
  echo odd
else
  echo even
fi

-- 
	Dan Nelson
	dnelson@xxxxxxxxxxxxxxx



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