This question already has an answer here:
-
Cannot debug simple ksh programme
2 answers
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?
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.
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))
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}"