797 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/bashdefines the interpreter for the script.read -p "Enter a number: " numberprompts the user for input and stores it in thenumbervariable.echo $number | revpipes the number to therevcommand, which reverses the characters. The output is captured in thereversed_numbervariable.- 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/bashdefines the interpreter for the script.echo "Enter a number"prompts the user to enter a number on the terminal.read numreads the user’s input and stores it in the variable namednum. This variable now holds the integer value entered by the user.reverse=0initializes a variable namedreverseto 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 ofnumis greater than 0. This loop iterates through each digit of the original number.remainder=$(( $num % 10 ))calculates the remainder obtained by dividingnumby 10. This effectively extracts the last digit of the number and stores it in theremaindervariable.reverse=$(( $reverse * 10 + $remainder ))updates thereversevariable. It multiplies the current value ofreverseby 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 numbernumby performing integer division by 10. This effectively preparesnumfor the next iteration of the loop.
- Finally, we print the reversed number using echo.