Here is a simple way to detect if a number is odd or even through a bash script.
Please pilfer and adapt to your needs!
There are a couple of other ways discussed, e.g. at the stackoverflow site, but
I saw this one nowhere before.
One explained trick consists of doing a modulo by two ( " % 2 ") of your number.
if the modulo is 1, you know you have an odd number; if "0", it is an even number.
Some devs are beautiful regex acrobats and use that. (I'm in awe. Really.)
You can browse through the following pages to get a taste of the problem -- and
of some answers.
https://www.ask.com/web?qsrc=1&o=0&l=di ... archTopBox
~~~~~~~~~~~~
I was getting nowhere with either in a script. I took a break.
After coffee, I thought: " Why not isolate the last digit of a number in a string
and compare it with the typical odd or even series?"
And the case function is the obvious to use for that. So here goes:
Code: Select all
#!/bin/bash
# Note: it has to be bash. See the $o variable below;
# ash does not know what to do with $o-1 in the context.
#
# /opt/local/bin/OddOrEven.sh
# Or store in any "bin" directory in your $PATH.
#
# Usage: OddOrEven.sh $1
# OR
# by itself: OddOrEven.sh, and answer the prompt.
#
# Examples: OddOrEven.sh 111 # OddOrEven.sh 32
#
# # © Christian L'Écuyer, Gatineau (Qc), Canada, 2018/02/20. GPL3.
# (Alias musher0 [forum Puppy].) #
####
N=$1
if [ "$N" = "" ];then
echo "Please type a number."
read N
fi
o="${#N}" # ash does not know what to do with "${N:($o-1):1}" in the following.
case "${N:($o-1):1}" in
1|3|5|7|9) echo -e "\n\t$N is an odd number.\n" ;; # If odd number.
0|2|4|6|8) echo -e "\n\t$N is an even number.\n" ;;
esac