Shell program to read a number and reverse the number

by on April 8, 2008 · 7 comments

  1. #!/bin/bash
  2. # Shell program to read a number and reverse the number
  3. # for example 123 should output as 321
  4. # -----------------------------------------------
  5. # Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
  6. # This script is licensed under GNU GPL version 2.0 or above
  7. # -------------------------------------------------------------------------
  8. # This script is part of nixCraft shell script collection (NSSC)
  9. # Visit http://bash.cyberciti.biz/ for more information.
  10. # -------------------------------------------------------------------------
  11.  
  12. echo -n "Enter number : "
  13. read n
  14.  
  15. # store single digit
  16. sd=0
  17.  
  18. # store number in reverse order
  19. rev=""
  20.  
  21. # store original number
  22. on=$n
  23.  
  24. # use while loop to caclulate the sum of all digits
  25. while [ $n -gt 0 ]
  26. do
  27. sd=$(( $n % 10 )) # get Remainder
  28. n=$(( $n / 10 )) # get next digit
  29. # store previoues number and current digit in rev
  30. rev=$( echo ${rev}${sd} )
  31. done
  32.  
  33. echo "$on in a reverse order $rev"


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • kumar anurag

    yeah, it was good

  • gagan lpu

    nice explaination

  • md parwez alam

    it is good, but straight forward, there must be some different logic.

  • Anonymous

    it was good

  • IQ154

    there is a flaw in your program
    if i enter 004
    the output should be 400
    but instead it gives 4 ?!
    how will you correct this

  • rakesh rai ct

    nice explain…….

  • Sanjib mishra

    Hey gd bt will not work for negetive number ….

Previous Script:

Next Script: