"[: s: integer expression expected" error in Bash script
This Bash script produces multiple "integer expression expected" errors when run:
echo "Enter string"
read str
len=`echo $str|wc -c`
len=`expr $len - 1`
i=0
j=1
l=`expr $len / 2`
while [ $i -le $l ]
do
start=`echo $str|cut -c $j`
end=`echo $str|cut -c $len`
echo $start
echo $end
if [ $start -ne $end ]
then
echo "not palindrome"
exit 0
fi
len=`expr $len - 1`
i=`expr $i + 1`
j=`expr $j + 1`
done
echo "string is palindrome"This is the output, including errors:
Enter string
saurabh
s
h
main.bash: line 18: [: s: integer expression expected
a
b
main.bash: line 18: [: a: integer expression expected
u
a
main.bash: line 18: [: u: integer expression expected
r
r
main.bash: line 18: [: r: integer expression expected
string is palindrome What is wrong in the script?
01 Answer
Instead of using external commands like wc, expr, cut, you can and should use bash internal string manipulation commands. Also, your script is suited to use bash arithmetic operations.
So, I have revised your script as shown below. See also my comments in the script.
#!/bin/bash
echo -n "Enter a string > "
read str
#len=`echo $str|wc -c`
#len=`expr $len - 1`
# You could use just `echo -n ...` and skipped the subtraction.
# But, for a better alternative use this:
let len=${#str}
let i=0
let j=1
#l=`expr $len / 2`
let l=len/2
while (( i < l )) ; do #start=`echo $str|cut -c $j` start=${str:j-1:1} #end=`echo $str|cut -c $len` end=${str:len-1:1} echo "$start" '=?' "$end" if [[ "$start" != "$end" ]] ; then echo "Not a palindrome" exit 0 fi #len=`expr $len - 1` let len=len-1 #i=`expr $i + 1` let i++ #j=`expr $j + 1` let j++
done
echo "String is a palindrome"This script can still be optimized a bit further. This is left as an exercise for you! ☺
Please, note that if you are using non-ASCII characters in your test string, the appropriate locale should be set. For example:
$ LANG=C.UTF-8 ./pal.sh
Enter string > ΝΙΨΟΝΑΝΟΜΗΜΑΤΑΜΗΜΟΝΑΝΟΨΙΝ
Ν =? Ν
Ι =? Ι
Ψ =? Ψ
Ο =? Ο
Ν =? Ν
Α =? Α
Ν =? Ν
Ο =? Ο
Μ =? Μ
Η =? Η
Μ =? Μ
Α =? Α
String is a palindrome
$ LANG=C ./pal.sh
Enter string > ΝΙΨΟΝΑΝΟΜΗΜΑΤΑΜΗΜΟΝΑΝΟΨΙΝ
� =? �
Not a palindrome