Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number is even in shell

Tags:

bash

math

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)

like image 441
rabotalius Avatar asked Jul 31 '13 02:07

rabotalius


2 Answers

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
like image 199
jderefinko Avatar answered Oct 06 '22 13:10

jderefinko


You can do a simple :

eCheck=$(( $newY & 1 ))

to utilize the bitwise operators in bash.

like image 30
blackSmith Avatar answered Oct 06 '22 13:10

blackSmith