Check if the number in the shell is equal

I need to check if the number is even.

Here is what I have 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 this be? 281/2 = 140.5

I also tried using bc , but it went into an infinite loop eCheck=$(echo "scale=1;$newY%2" | bc)

+4
source share
6 answers

You can make simple:

 eCheck=$(( $newY & 1 )) 

use bitwise operators in bash.

+6
source

Nicky is right, "%" is the module and gives you the rest 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 
+4
source

The % operator calculates the remainder. So, 281 % 2 - 1 , because 281 divided by 2 is 140 with a remainder of 1 .

+2
source

You are so close! Think of it this way. There are only two possible answers for Y in the expression

 Y = X % 2 

for ALL X values. What is it? Play with multiple X values ​​to see if you can find the values ​​for Y.

Further, is there anything you can define about what the value of Y says about the value of X? That is, can you use the Y value to answer the problem you are trying to solve?

+1
source
 #!bin/bash echo "Type the input integer, followed by [Enter]:" read x if [ $((x%2)) -eq 0]; then echo "$x is even" else echo "$x is odd" fi Yes "%" is modulo, it gives you the remainder, like others have mentioned Thought this answer might be helpful to new linux users 
+1
source

This can be done using expr

 evenCheck=$(expr $newY % 2) if [ $evenCheck = 0 ] ; then echo "number is even"; else echo "number is odd"; fi done 
0
source

Source: https://habr.com/ru/post/1494402/


All Articles