bash shell scripting problem: Write a script to determine if a parameter supplie
ID: 3589297 • Letter: B
Question
bash shell scripting problem:
Write a script to determine if a parameter supplied to the script is a palindrome or not. A palindrome is a string that reads the same forward and backward. To accomplish this, you will need to loop from 0 to the halfway point in the string and compare the character at location i to the character at location length – i – 1 where length is the length of the string. If, after passing halfway through, the two compared characters match in each iteration, then output the parameter and that it is a palindrome, else output the parameter and that it is not a palindrome.
Explanation / Answer
#!/bin/bash
echo "Parameter supplied is Palindrome or not"
inputString=$1
isPalindrome=1
# Get length of the inputString.
len=${#inputString}
#get the halfway value by dividing len/2.
halfway=$((len/2))
for ((i=1;i<=halfway;i++))
do
c1=`echo $inputString|cut -c$i`
c2=`echo $inputString|cut -c$len`
if [ $c1 != $c2 ]
then
isPalindrome=0
break 2
fi
let len--
done
if [ isPalindrome -eq 1 ]
then
echo ""$inputString" is a Palindrome"
else
echo ""$inputString" is not a Palindrome"
fi
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.