How to Reverse a String using Unix Shell Programming?

Bash is a shell or command line interpreter that serves as a programming language for executing commands and scripts. It allows users of Unix-like systems and Windows (via Windows Subsystem for Linux) to control the operating system using text-based commands.

In this article, we will solve the problem of reversing a string using Shell scripting. Given a string input, we need to print its reverse using Shell programming techniques.

Input : str = "Hello"
Output : "olleH"
Explanation : Reverse order of string "Hello" is "olleH".

Input : str = "yam"
Output : "may"

Approach to Find The Solution

  • Declare two variables: one to store the input string and another to store the reversed string.
  • Find the length of the given string using ${#str} syntax.
  • Traverse the string from [length - 1]th index to 0 using a for loop.
  • Extract each character and append it to the reversed string variable.
  • Finally, print the reversed string using echo.

Example

#!/bin/bash
# declaring variable to store string
# and catching the string passed from shell
str="$1"
reversed_string=""
# finding the length of string
len=${#str}
# traverse the string in reverse order.
for (( i=$len-1; i>=0; i-- ))
do
   reversed_string="$reversed_string${str:$i:1}"
done
# printing the reversed string.
echo "$reversed_string"

How It Works

  • str="$1" − Captures the first command-line argument as the input string.
  • len=${#str} − Gets the length of the string using parameter expansion.
  • ${str:$i:1} − Extracts one character at position $i from the string.
  • The loop iterates from the last character to the first, building the reversed string.

Input

Hello

Output

olleH

Alternative Methods

Using rev Command

#!/bin/bash
str="$1"
echo "$str" | rev

Using Recursion

#!/bin/bash
reverse_string() {
    local str="$1"
    if [ ${#str} -le 1 ]; then
        echo -n "$str"
    else
        echo -n "${str: -1}"
        reverse_string "${str%?}"
    fi
}

str="$1"
reverse_string "$str"
echo

Conclusion

Reversing a string in Shell programming can be accomplished using loops, built-in commands like rev, or recursive functions. The loop-based approach provides clear control over the string manipulation process, while the rev command offers a simpler one-line solution.

Updated on: 2026-03-17T09:01:38+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements