Bad substitution error in ksh [duplicate]

2019-08-03 01:37发布

This question already has an answer here:

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?

3条回答
地球回转人心会变
2楼-- · 2019-08-03 02:19

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.

查看更多
ら.Afraid
3楼-- · 2019-08-03 02:23

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}"
查看更多
贼婆χ
4楼-- · 2019-08-03 02:30

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))
查看更多
登录 后发表回答