gpt4 book ai didi

linux - shell 代码中的语法错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:37:56 24 4
gpt4 key购买 nike

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

最佳答案

#!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 ...;阅读

关于linux - shell 代码中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com