无法调试简单的ksh程序 [英] Cannot debug simple ksh programme

查看:106
本文介绍了无法调试简单的ksh程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了此示例KornShell(ksh)代码,但在if子句期间出现了严重的替换错误.

I wrote this sample KornShell (ksh) code but it is getting bad substitution error during the if clause.

while ((i < $halflen))
do
 if [[${strtochk:i:i}==${strtochk:j:j}]];then
       i++
       j--
 else
  ispalindrome = false
 fi
done

请帮助.

注意:我使用的是ksh88,而不是ksh93.

NB: I am using ksh88, not ksh93.

推荐答案

shell语法对空格非常敏感:

shell syntax is very whitespace sensitive:

  • [[的缩写是命令的名称,不仅仅是语法,因此它后面必须有一个空格.
  • [[的最后一个参数必须为]],因此必须在其前面加上一个空格.
  • [[的工作方式取决于接收到的参数的数量,因此您要在==
  • 周围留空格
  • 在变量分配中,=周围不能有空格.
  • [[ is acually the name of a command, it's not just syntax, so there must be a space following it.
  • The last argument of [[ must be ]], so it needs to be preceded by a space.
  • [[ works differently depending on the number of arguments it receives, so you want to have spaces around ==
  • In a variable assignment, you must not have spaces around =.

提示:

  • 一旦发现这不是回文,break退出while循环
  • 您可能正在逐个字符地检查字符,所以您想要${strtochk:i:1}
  • i++j--是算术表达式,而不是命令,因此需要双括号.
  • 您是从i=0j=$((${#strtochk} - 1))开始的吗?
  • once you figure out it's not a palindrome, break out of the while loop
  • you are probably checking character by character, so you want ${strtochk:i:1}
  • i++ and j-- are arithmetic expressions, not commands, so you need the double parentheses.
  • are you starting with i=0 and j=$((${#strtochk} - 1))?
while ((i < halflen))
do
    if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then
        ((i++))
        ((j--))
    else
        ispalindrome=false
        break
    fi
done

检查您的系统是否具有 rev ,则只需执行以下操作:

Check if your system has rev, then you can simply do:

if [[ $strtochk == $( rev <<< "$strtochk" ) ]]; then
    echo "'$strtochk' is a palindrome"
fi


function is_palindrome {
     typeset strtochk=$1
     typeset -i i=1 j=${#strtochk}
     typeset -i half=$(( j%2 == 1 ? j/2+1 : j/2 ))
     typeset left right

     for (( ; i <= half; i++, j-- )); do
         left=$( expr substr "$strtochk" $i 1 )
         right=$( expr substr "$strtochk" $j 1 )
         [[ $left == $right ]] || return 1
     done
     return 0
}

if is_palindrome "abc d cba"; then
    echo is a palindrome
fi

这篇关于无法调试简单的ksh程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆