0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Reverse a Number with Output and Explanation

Use read number; echo "$number" | rev in Bash to reverse a number by treating it as a string and reversing its characters.
📋

Examples

Input12345
Output54321
Input1000
Output0001
Input7
Output7
🧠

How to Think About It

To reverse a number in Bash, think of the number as a string of characters. Then reverse the order of these characters to get the reversed number. This works because reversing digits is like reversing letters in a word.
📐

Algorithm

1
Get the input number as a string.
2
Reverse the string characters.
3
Print the reversed string as the reversed number.
💻

Code

bash
read -p "Enter a number: " number
reversed=$(echo "$number" | rev)
echo "Reversed number: $reversed"
Output
Enter a number: 12345 Reversed number: 54321
🔍

Dry Run

Let's trace input 12345 through the code

1

Read input

number="12345"

2

Reverse string

echo "12345" | rev outputs "54321"

3

Print result

Print "Reversed number: 54321"

Input NumberReversed Output
1234554321
💡

Why This Works

Step 1: Input as string

The number is read as a string so we can manipulate its characters easily with Bash tools.

Step 2: Use rev command

The rev command reverses the order of characters in the string, effectively reversing the digits.

Step 3: Output reversed number

The reversed string is printed as the reversed number, showing the digits in reverse order.

🔄

Alternative Approaches

Using a loop to reverse digits
bash
read -p "Enter a number: " num
rev_num=0
while [ $num -gt 0 ]; do
  digit=$(( num % 10 ))
  rev_num=$(( rev_num * 10 + digit ))
  num=$(( num / 10 ))
done
echo "Reversed number: $rev_num"
This method treats the number as an integer and reverses digits mathematically, avoiding string commands but losing leading zeros.
Using parameter expansion
bash
read -p "Enter a number: " num
rev_num=""
for (( i=${#num}-1; i>=0; i-- )); do
  rev_num+="${num:i:1}"
done
echo "Reversed number: $rev_num"
This uses Bash string slicing to reverse characters manually, useful if <code>rev</code> is not available.

Complexity: O(n) time, O(n) space

Time Complexity

Reversing the string takes time proportional to the number of digits, so O(n).

Space Complexity

The reversed string requires extra space proportional to the input size, so O(n).

Which Approach is Fastest?

Using rev is fastest and simplest. Loop-based reversal is slower but works without external commands.

ApproachTimeSpaceBest For
Using rev commandO(n)O(n)Simple and fast string reversal
Loop with math operationsO(n)O(1)Numeric reversal without leading zeros
Bash parameter expansion loopO(n)O(n)Pure Bash string reversal without external tools
💡
Use the rev command for a simple and fast way to reverse strings in Bash.
⚠️
Forgetting that reversing as a string keeps leading zeros, which may not be desired for numeric operations.