197 Method 1: Using the
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 thenumber
variable.echo $number | rev
pipes the number to therev
command, which reverses the characters. The output is captured in thereversed_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 namednum
. This variable now holds the integer value entered by the user.reverse=0
initializes a variable namedreverse
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 ofnum
is greater than 0. This loop iterates through each digit of the original number.remainder=$(( $num % 10 ))
calculates the remainder obtained by dividingnum
by 10. This effectively extracts the last digit of the number and stores it in theremainder
variable.reverse=$(( $reverse * 10 + $remainder ))
updates thereverse
variable. It multiplies the current value ofreverse
by 10 (shifting any existing digits one place to the left) and adds the extractedremainder
(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 numbernum
by performing integer division by 10. This effectively preparesnum
for the next iteration of the loop.
- Finally, we print the reversed number using echo.