In this tutorial, I will share a simple script to reverse a number provided through command line in Unix/Linux Operating System. The script will print the reversed digits of provided number and if no number or more than one numbers are provided, then it will print an error. Algorithm is fairly simple :
nbe the given number.
remequals to 0.
- Find last digit of
nand store in
rem = n % 10.
- Now calculate
rev = rev * 10 + rem.
- Remove the last digit from
n = n / 10.
- Check if
nis greater than 0, if yes goto step 3, else step 7.
- Print the number
revwhich is reverse of number
- Enter the following line which tell the terminal while running the script to use
bashto run the script.
- Now check if only a single argument is provided, if yes then its Ok, otherwise print an error message regarding this and exit the script.
if [ $# -ne 1 ] then echo "Usage : $0 number" echo "To print the reverse of input number" echo "example for 1234 answer will be 4321" echo "provide a single number as parameter to script" exit 1 fi
- Now assign the 1st parameter value to
n, 0 to
remare temporary variables)
n=$1 rev=0 rem=0
- Now in a while loop, which will run until value of
nis greater than 0, apply the algorithm discussed above as follows.
while [ $n -gt 0 ] do rem=`expr $n % 10` rev=`expr $rev \* 10 + $rem` n=`expr $n / 10` done
- Now print the value of variable
revwhich contains the digits in the reverse order as compared to original number provided.
echo "Reversed number is : $rev"
Here is an image of the working sample of the script. (Script name is reverse stored in Documents folder)
You can download the sample script from here.
Incoming search terms:
- program for reverse of a number in unix (1)
- reverse of 4 digit no in linux prpgramming (1)
- reverse of a digit/shell program (1)
How To Find Sum of Sum of digits of a number using Shell Scripting How To find out Biggest number among the three provided numbers through command line using Shell Scripting How To Find Sum of Two Numbers which are supplied as Command Line Arguments How to Embed PHP using Different Tag Types How To find Factorial of a number in C