I need to check if a number is even.
Here's what I've tried.
newY="281"
eCheck=$(( $newY % 2 ))
echo $newY
echo $eCheck
while [ $eCheck -eq 0 ]; do
newY=$((newY-1))
eCheck=$(( $newY % 2 ))
echo $newY
done
...
returns eCheck = 1
how can it be? 281/2 = 140.5
i've also tried using bc
, but it went into an infinite loop eCheck=$(echo "scale=1;$newY%2" | bc)
Nici is right, "%" is the modulo, and gives you the remainder of the division.
Your script can be simplified as follows :
if [[ $((var % 2)) -eq 0 ]];
then echo "$var is even";
else echo "$var is odd";
fi
You can do a simple :
eCheck=$(( $newY & 1 ))
to utilize the bitwise operators in bash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With