shell代码中的语法错误

时间:2014-04-30 01:26:33

标签: linux shell scripting syntax-error

我是shell脚本的初学者。 任何人都可以告诉我,这段代码中的错误是什么?

#!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

1 个答案:

答案 0 :(得分:4)

#!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

这就是功能问题。您也可以考虑:

  1. 使用"${#a}"获取参数a
  2. 中的字符数
  3. 使用"${a: $x:$y}"获取a扩展的子字符串。
  4. 使用$()代替反引号进行命令替换。它更好。
  5. 使用read -p代替echo …; read