Cannot debug simple ksh programme

后端 未结 2 973
臣服心动
臣服心动 2021-01-24 03:02

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}==${str         


        
相关标签:
2条回答
  • 2021-01-24 03:21

    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))
    
    0 讨论(0)
  • 2021-01-24 03:37

    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
    
    0 讨论(0)
提交回复
热议问题