0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Reverse a String with Example

You can reverse a string in Bash using rev command like echo "yourstring" | rev or using parameter expansion with a loop to reverse manually.
📋

Examples

Inputhello
Outputolleh
InputBash123
Output321hsaB
Input
Output
🧠

How to Think About It

To reverse a string in Bash, think of reading the string from the end to the start and building a new string by adding characters one by one in reverse order. Alternatively, use the built-in rev command that does this efficiently.
📐

Algorithm

1
Get the input string.
2
Initialize an empty string to hold the reversed result.
3
Loop through the input string from the last character to the first.
4
Add each character to the reversed string.
5
Output the reversed string.
💻

Code

bash
#!/bin/bash
read -p "Enter a string: " str
reversed=""
len=${#str}
for (( i=len-1; i>=0; i-- )); do
  reversed+=${str:i:1}
done
echo "$reversed"
Output
Enter a string: hello olleh
🔍

Dry Run

Let's trace reversing the string 'abc' through the code

1

Input string

str = 'abc'

2

Initialize reversed

reversed = ''

3

Loop i=2 (last char)

reversed = 'c'

4

Loop i=1

reversed = 'cb'

5

Loop i=0

reversed = 'cba'

6

Output

cba

IterationIndex iCharacterReversed string
12cc
21bcb
30acba
💡

Why This Works

Step 1: Reading input

The script reads the string from the user using read.

Step 2: Looping backwards

It uses a for loop starting from the last character index to zero to access characters in reverse order.

Step 3: Building reversed string

Each character is appended to the reversed variable, creating the reversed string step by step.

🔄

Alternative Approaches

Using rev command
bash
#!/bin/bash
read -p "Enter a string: " str
echo "$str" | rev
This is the simplest and fastest method but requires the <code>rev</code> utility to be installed.
Using awk
bash
#!/bin/bash
read -p "Enter a string: " str
echo "$str" | awk '{for(i=length;i!=0;i--)x=x substr($0,i,1);}END{print x}'
Uses awk to reverse string, useful if <code>rev</code> is not available but less readable.

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

Time Complexity

The script loops through each character once, so time grows linearly with string length.

Space Complexity

It creates a new string to hold the reversed result, so space also grows linearly.

Which Approach is Fastest?

Using the rev command is fastest and simplest, while manual loops are more flexible but slower.

ApproachTimeSpaceBest For
Manual loopO(n)O(n)Learning and no external tools
rev commandO(n)O(n)Quick and efficient string reversal
awk methodO(n)O(n)When rev is unavailable
💡
Use the rev command for a quick and simple string reversal in Bash.
⚠️
Beginners often try to reverse strings with incorrect indexing or forget Bash strings are zero-indexed.