How can I write a shell predicate function event that takes an integer argument and tests if it's even or not?


Use the modulo operator



iseven() {
    return $(($1 % 2))

if iseven 10; then echo 10 is even; else echo 10 is odd; fi
if iseven 11; then echo 11 is even; else echo 11 is odd; fi

Check the remainder:

[ $((var1%2)) -ne 0 ] && echo "odd"
[ $((var2%2)) -eq 0 ] && echo "even"

...is the way to go. Although I am confused with your later question edit asking your "predicate function event".


Actually bash has a bitwise AND operator, so a bitwise AND with 1 is the same conceptually with useing % 2 to get a remainder mod 2

[ $((var & 1)) -ne 0 ] && echo "odd"
[ $((var & 1)) -eq 0 ] && echo "even"

(and save microseconds by skipping a division)

EDIT: removed expression with ! that somehow was history and a logical not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.