我是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
答案 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
这就是功能问题。您也可以考虑:
"${#a}"
获取参数a
。"${a: $x:$y}"
获取a
扩展的子字符串。$()
代替反引号进行命令替换。它更好。read -p
代替echo …; read
。