String Reverse

To reverse a String in Bash, iterate over the characters of string from end to start using a For loop or While Loop, and append characters such that the order of characters is reversed.

Or we can also use rev command to reverse a string.

In this tutorial, we will write an example Bash script to demonstrate how to reverse a string using both the looping techniques, and with rev command.

Examples

String Reverse using For Loop

In the following script, we take an input string in s. We take a variable strlen to store the length of the string s.

In the For loop, we start at index i of the last character in the string, and decrement the index during each iteration. Append the character at current index to the end of the resulting reverse string revstr.

Once the loop is finished executing, revstr contains reversed value of given string s.

Example.sh

</>
Copy
s="Hello World"
strlen=${#s}
for (( i=$strlen-1; i>=0; i-- ));
do
    revstr=$revstr${s:$i:1}
done
echo "Original String : $s"
echo "Reversed String : $revstr"

Output

Original String : Hello World
Reversed String : dlroW olleH

String Reverse using While Loop

The logic remains the same as that of For Loop.

Example.sh

</>
Copy
s="Hello World"
strlen=${#s}
i=$((strlen-1))
while [ $i -ge 0 ]
do
    revstr=$revstr${s:$i:1}
    i=$((i-1))
done
echo "Original String : $s"
echo "Reversed String : $revstr"

Output

Original String : Hello World
Reversed String : dlroW olleH

String Reverse using rev Command

In the following script, we use rev command to reverse a string s.

Example.sh

</>
Copy
s="Hello World"
revstr=`echo $s | rev`
echo "Original String : $s"
echo "Reversed String : $revstr"

Output

Original String : Hello World
Reversed String : dlroW olleH

Conclusion

In this Bash Tutorial, we have learnt how to reverse a string in Bash using For loop, While loop or rev command.