Bad substitution error in ksh [duplicate]

依然范特西╮ 提交于 2020-01-15 09:13:48

问题


The following KornShell (ksh) script should check if the string is a palindrome. I am using ksh88, not ksh93.

#!/bin/ksh
strtochk="naman"
ispalindrome="true"
len=${#strtochk}
i=0
j=$((${#strtochk} - 1))
halflen=$len/2
print $halflen
while ((i < $halflen))
do
 if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then
       (i++)
       (j--)
 else
  ispalindrome="false"
  break
 fi
done

print  ispalindrome

But I am getting bad substitution error at the following line : if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then

Can someone please let me know what I am doing wrong?


回答1:


The substring syntax in ${strtochk:i:1} and ${strtochk:j:1} is not available in ksh88. Either upgrade to ksh93, or use another language like awk or bash.




回答2:


You can replace your test with this portable line:

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

You also need to replace the dubious

halflen=$len/2

with

halflen=$((len/2))

and the ksh93/bash syntax:

$((i++))
$((j--))

with this ksh88 one:

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



回答3:


How about this KornShell (ksh) script for checking if an input string is a palindrome.

isPalindrome.ksh

#!/bin/ksh 

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
echo Enter the string
read s
echo $s > temp
rvs="$(rev temp)"
if [ $s = $rvs ]; then
    echo "$s is a palindrome"
else
    echo "$s is not a palindrome"
fi  
echo "Exiting: ${PWD}/${0}"


来源:https://stackoverflow.com/questions/20962928/bad-substitution-error-in-ksh

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