Doing a modulo in /bin/sh??
Dan Nelson
dnelson at allantgroup.com
Wed Aug 31 18:42:10 GMT 2005
In the last episode (Aug 31), Gary Kline said:
> I can grab the results of "w=$date+%U)"; in C an use the modulo
> operator; is there a way to do this is /bin/sh? ot zsh?
>
> #/bin/sh
> w=$(date +%U)
> echo "w is $w";
> (even=$(w % 2 )); ## flubs.
> echo "even is $even"; ## flubs.
>
> if [ $even -eq 0 ] ## flubs, obv'ly.
> then
> echo "week is even";
> else
> echo "week is odd";
> fi
For the simple even/odd case, you can AND with 1:
even=$(( w & 1 ))
For the general case:
xmodn=$(( x - ((x / n) * n) ))
which works since sh's arithmetic evaluator is integer-only.
zsh has the % modulo operator, so xmod=$(( x % n )) .
--
Dan Nelson
dnelson at allantgroup.com
More information about the freebsd-questions
mailing list