Friday, May 25, 2018

Check a string if it is palindrome in shell script using rev command and without the use of rev command,Linux Teacher Sourav,Kolkata 09748184075

#/bin/sh
#25/05/2018

#in our class there is a very common task to see a string is palindrome or not

#for example aba is a string that will be same when altered from the opposite direction

#another example is 1991
#do you understand the assignment
#yes

#so let us ask the user to give us a string

echo "Please enter a string to be checked whether it is a palindrom"

read answer

echo "the string you entered is stored in the answer variable and it is $answer"

#there is an utility called rev by which we can do it just by a command

reverse=`echo $answer | rev`
#echo $reverse
#if [ $answer == $reverse ] ; then

#echo "the entered string is palindrome"

#else

#echo "the entered string is not palindrome"

#fi


#so it's working,however if we like we can do it without the use of rev command

#this backtick is used for evaluation ,like whatever inside the backtick will be evaluated

#and then be assigned to the left side

#wso to perform the same task without using rev

#we need to find the length of the string(for example the length of hello is 5

lenofword=$(echo -n $answer | wc -m)

echo the length of the word is $lenofword


#i am using shell command wc -m to get the character count,what could the problem
#for character we use -c, right?


#yes my mistake
#for some reason it's not working right now ,let me search a solution and will get back to you
#ok. leave it here. now can we work on the script i shared.


#yes sure

#i will come back to this later
#sometimes in shell script i forget the syntax,will check surely
reverse=""
for(( i=lenofword;i>=0;i--)) ; do
reverse+=${answer:i:1}



done

#echo $reverse

if [ $answer == $reverse ] ; then

echo "the entered string is palindrome"

else

echo "the entered string is not palindrome"

fi

No comments:

Post a Comment