Question

I am a beginner in shell scripting. Can anyone please tell me, what is the error in this code?

#!usr/bin/sh
#palindrome
echo "enter the number"
read a

len = ` echo $a | wc -c `
while [ $len -ne 0 ]
do
a1 = ` echo $a | cut -c $len `
rev = ${rev}${a1}
len = ` expr $len - 1 `
done
if [ $a == $rev ]
then 
echo " palindrome"
else
echo "not a palindrome"
fi
Was it helpful?

Solution

#!usr/bin/sh # <-- This is probably not where `sh` is. You need the absolute path.
             #     sh is /bin/sh on many systems

#palindrome
echo "enter the number"
read a

len = ` echo $a | wc -c ` # <-- shell doesn't allow whitespace around assignments
                          #     Do len=`echo $a | wc -c`
while [ $len -ne 0 ]
do
a1 = ` echo $a | cut -c $len `
rev = ${rev}${a1}
len = ` expr $len - 1 `
done
if [ $a == $rev ] # <-- use a single `=` sign.
then 
echo " palindrome"
else
echo "not a palindrome"
fi

That's it for the functional issues. You may also consider:

  1. Use "${#a}" to get the number of characters in the parameter a.
  2. Use "${a: $x:$y}" to get a substring of the expansion of a.
  3. Use $() instead of backticks for command substitution. It nests better.
  4. Use read -p instead of echo …; read.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top