Cannot debug simple ksh programme

爷,独闯天下 提交于 2019-12-02 07:42:31

问题


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

Please help.

NB: I am using ksh88, not ksh93.


回答1:


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 =.

Tips:

  • 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

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



回答2:


You are using ksh88 but the code you tried is using ksh93 feature missing for the 88 version.

You need to replace

if [[${strtochk:i:i}==${strtochk:j:j}]];then

with these portable lines:

if [ "$(printf "%s" "$strtochk" | cut -c $i)" =
     "$(printf "%s" "$strtochk" | cut -c $j)" ]; then

and the incorrect:

i++
j--

with:

i=$((i+1))
j=$((j-1))


来源:https://stackoverflow.com/questions/20955251/cannot-debug-simple-ksh-programme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!