Thursday, March 20, 2014

Reverse of a Number – Linux Shell Scripting

Problem Question


Write a script to display the given number in reverse order.

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter (integer) and reverse it. A sample run should yield the output of the following kind:
sh ReverseNumber.sh 123
the output should be 321.

Code



#*ReverseNumber*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 20-03-2014
n=$1
a=""
while [ $n -gt 0 ]
 do
  a=$( echo ${a}$(( $n % 10)) )
  n=$(( $n / 10))
 done
echo $1 in Reverse Order is $a

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

n=$1 -> -> We save the command line argument into a variable named ‘n’. This variable is required since we are going to use it to segregate the digits by recursively dividing it with 10 and storing the remainder.

a="" -> ‘a’ is our string variable here which is going to hold he answer, the reverse number.

while [ $n -gt 0 ] -> Our main loop of the program which is going to extract the digits one by one from the variable ‘n’ and store it into our variable ‘a’. For this purpose we us the line a=$( echo ${a}$(( $n % 10)) ) where we do the following –
The value of the last digit is extracted by applying modulus function to the number. We use the echo command to display the current value of variable ‘a’ followed by this extracted digit. But since we enclose this echo inside another $, we store the result of the echo to the variable ‘a’ rather than displaying it on the terminal. Thus we build up the string ‘a’ holding the reverse of the number as we traverse through the loop.

n=$(( $n / 10)) -> Since we have used the last digit in the above line, thus we reject it using this line of code so that we are left with the remaining part of the number.

do done -> While loop block delimiters.

echo $1 in Reverse Order is $a -> We this time use the echo command of the linux shell to display the output to the screen. The output, i.e. the reverse number is stored in variable ‘a’ while ‘$1’ denotes the command line argument, i.e. our original number.

Output(s)



No comments:

Post a Comment

Need help?