Home Linux Shell Script to Reverse a Number

Shell Script to Reverse a Number

by Anup Maurya
17 minutes read

In this article, you’ll learn how to create a Shell Script to Reverse a Number. For example, if the input is `12345`, the script will output `54321`.

There are two main approaches we can take:

Method 1: Using the rev command

This method works well for simple character reversal. Here’s a script that utilizes rev

#!/bin/bash

# Read the number from the user
read -p "Enter a number: " number

# Reverse the number using rev and print the result
reversed_number=$(echo $number | rev)
echo "The reversed number is: $reversed_number"

Explanation:

  • #!/bin/bash defines the interpreter for the script.
  • read -p "Enter a number: " number prompts the user for input and stores it in the number variable.
  • echo $number | rev pipes the number to the rev command, which reverses the characters. The output is captured in the reversed_number variable.
  • Finally, we print the reversed number using echo.

Method 2: Mathematical Approach

#!/bin/bash
 
echo "Enter a number"
read num
reverse=0
 
while [ $num -gt 0 ]
do
    remainder=$(( $num % 10 )) 
    reverse=$(( $reverse * 10 + $remainder )) 
    num=$(( $num / 10 )) 
done
 
echo "Reversed number is : $reverse"

Explanation:

  • #!/bin/bash defines the interpreter for the script.
  • echo "Enter a number" prompts the user to enter a number on the terminal.
  • read num reads the user’s input and stores it in the variable named num. This variable now holds the integer value entered by the user.
  • reverse=0 initializes a variable named reverse to 0. This variable will be used to store the reversed number.
  • while [ $num -gt 0 ] starts a loop that continues as long as the value of num is greater than 0. This loop iterates through each digit of the original number.
    • remainder=$(( $num % 10 )) calculates the remainder obtained by dividing num by 10. This effectively extracts the last digit of the number and stores it in the remainder variable.
    • reverse=$(( $reverse * 10 + $remainder )) updates the reverse variable. It multiplies the current value of reverse by 10 (shifting any existing digits one place to the left) and adds the extracted remainder (the last digit) to the rightmost position. This builds the reversed number digit by digit.
    • num=$((num / 10)) removes the last digit from the original number num by performing integer division by 10. This effectively prepares num for the next iteration of the loop.
  • Finally, we print the reversed number using echo.

related posts

Leave a Comment

Enable Notifications OK No thanks