≡ Menu

Shell program to read a number and reverse the number

#!/bin/bash
# Shell program to read a number and reverse the number
# for example 123 should output as 321
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project 
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
echo -n "Enter number : "
read n
# store single digit
sd=0
# store number in reverse order
rev=""
# store original number
on=$n
# use while loop to caclulate the sum of all digits
while [ $n -gt 0 ]
do
    sd=$(( $n % 10 )) # get Remainder
    n=$(( $n / 10 ))  # get next digit
    # store previoues number and current digit in rev
    rev=$( echo ${rev}${sd} )
done
echo  "$on in a reverse order $rev"
{ 8 comments… add one }
  • sanjeeb October 19, 2013, 9:07 pm

    iq154
    if the cond is [ $n -ne 0 ] den it will work for negative integers

  • Sanjib mishra February 8, 2013, 3:44 am

    Hey gd bt will not work for negetive number ….

  • rakesh rai ct March 25, 2012, 10:54 am

    nice explain…….

  • IQ154 November 25, 2011, 4:53 pm

    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

  • md parwez alam March 10, 2010, 1:59 pm

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

  • gagan lpu June 4, 2009, 5:28 am

    nice explaination

  • kumar anurag April 19, 2009, 9:55 pm

    yeah, it was good

    • Anonymous July 11, 2011, 6:52 am

      it was good

Security: Are you a robot or human?

Leave a Comment