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 <http://cyberciti.biz/fb/>
# 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"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
9 comments… add one
  • Manojit Chakraborty Mar 11, 2017 @ 18:32

    it worked for me…..but I want to use a function,what change should i make here

  • sanjeeb Oct 19, 2013 @ 21:07

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

  • Sanjib mishra Feb 8, 2013 @ 3:44

    Hey gd bt will not work for negetive number ….

  • rakesh rai ct Mar 25, 2012 @ 10:54

    nice explain…….

  • IQ154 Nov 25, 2011 @ 16:53

    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 Mar 10, 2010 @ 13:59

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

  • gagan lpu Jun 4, 2009 @ 5:28

    nice explaination

  • kumar anurag Apr 19, 2009 @ 21:55

    yeah, it was good

    • Anonymous Jul 11, 2011 @ 6:52

      it was good

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.