Thursday, November 1, 2012

How to find whether string is palindrome or not in Unix


#############################################################
# To find whether the string is palindrome or not                                            #
#############################################################

#!/bin/ksh

# To make sure the sufficient arguments
if [ $# -ne 1 ]
then
  echo "Please enter one argument"
 exit -1
fi

# Declaring and assigning the values to the local variables
b=`echo $1 | wc -c `
c=$(( $b-1 ))
d=$(( $c/2 ))
flag=1
m=1

# Logical part to handle the palindrome calculations
while [ $m -le $d ]
do
    e=`echo $1 | cut  -c$c`
    f=`echo $1 | cut  -c$m`
    if [ $e != $f ]
      then
          flag=0
          break
    fi
     c=$(( $c-1 ))
     m=$(( $m+1 ))
done

  if [ flag -eq 0 ]
 then
echo "The string is not a palindrome"
else
echo "The string is palindrome"
fi
exit 0