Nandakumar Edamana
Share on:
@ R t f

Palindrome Test Using Shell Script


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