How to Reverse a String using Unix Shell Programming?

LinuxOperating SystemOpen Source

Bash is a shell or command line interpreter. It is a layer programming language that understands and executes the command that a user enters or can read commands from a script. Essentially Bash or Shell allows users of Unix-like systems and Windows via a Windows subsystem for Linux to control the innermost components of the Operating system using text-based commands.

In this article, we will discuss a problem to be solved by Shell scripting. We are given a String, and we need to print the reverse of that string using Shell Programming. For example,

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 strings, one to store the given string and the other to store reversed string.
  • Find the length of the given string.
  • Traverse the string from [length - 1]th index to 1 using a for a loop.
  • Append every character 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"

Input

Hello

Output

olleH
raja
Published on 29-Nov-2021 10:44:20
Advertisements