Monday, February 26, 2007

Reverse the digits of a number : BASH beginner


It used to be among our college assignments, a good one for BASH beginners.

#!/bin/sh
#Sum of all digits in a number

num=12334
mod=0
rev=0

echo "Number= $num"
while [ $num -gt 0 ]
do
mod=`expr $num % 10`
rev=`expr $rev \* 10 + $mod`
num=`expr $num / 10`
done

echo "rev= $rev"

$ ./reverse.sh
Number= 12334
rev= 43321

Also a one liner replacement of the above script

$ echo "12334" | rev
43321

1 comment:

Jitu said...

Hi Jadu,
we can use the command $ echo "123" | rev..
But is their any constraints for it..coz i have tried it on Bash Shell of Solaris 9,but it is not working..

Thanks in advance..

© Jadu Saikia www.UNIXCL.com