Nandakumar
Content Network

You are not logged in.
Click here to login.

Some part of this library is not public. You must register to get exclusive access. If you are already registered, click here to login.


Shell Programming >> 2017

Palindrome Test Using Shell Script

By | | License: proprietary


This script reverses a string and compares it with the original string to see whether it is a palindrome or not.

To reverse a string, a for loop is used that iterates the bash facility to take substrings. It takes the ith character of the given string, and prepends it to the variable that we use to store the reverse of it. Finally, it can be compared with the original string to see whether it is a palindrome or not.

Code
#!/bin/bash

echo -n "Enter a string: "
read str

for i in $(seq 0 ${#str}) ; do
	revstr=${str:$i:1}$revstr
done

echo "The given string is " $str
echo "Its reverse is " $revstr

if [ "$str" = "$revstr" ]; then
	echo "It is a palindrome."
else
	echo "It is not a palindrome."
fi

In the above code, we have used an expression ${str:$i:1}, which simply means take one character from the ith position. revstr=${str:$i:1}$revstr means revstr becomes this new character + the old revstr.


Keywords (click to browse): palindrome reverse string shell sh bash linux gnu unix script programming command-line

Palindrome Test Using Shell Script | Nandakumar Content Network
Copyright © 2015, 2016, 2017 Nandakumar Edamana.