【问题标题】:Syntax error in shell codeshell 代码中的语法错误
【发布时间】:2014-04-30 01:26:33
【问题描述】:

我是 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

【问题讨论】:

  • 嗨,欢迎来到 StackOverflow!首先尝试通过shellcheck 运行您的代码,以解决最基本的问题,然后用剩下的内容更新您的代码!

标签: linux shell scripting syntax-error


【解决方案1】:
#!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. 使用"${a: $x:$y}" 获取a 扩展的子字符串。
  3. 使用$() 代替反引号进行命令替换。它筑巢更好。
  4. 使用read -p 而不是echo …; read。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多