How can I write a shell predicate function event that takes an integer argument and tests if it's even or not?
3 Answers
Use the modulo operator
Example:
#!/bin/bash
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=7
[ $((var1%2)) -ne 0 ] && echo "odd"
var2=4
[ $((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