Search code examples
bashexpr

shell non integer argument in expr error


I wrote the following code in shell script:

num=$1
sum=0; rn=0
less=0; fact=0
while [ $num -gt 0 ]
do
rn=`expr $num % 10`
num=`expr $num / 10`
while [ $rn -gt 1 ]
do
less=`expr %rn - 1`
fact=`expr $rn \* less`
rn=`expr $rn - 1`
done
sum=`expr $sum + $fact`
done
echo $sum

but the terminal shows the following error without any line number : Terminal Error pic

Please tell me where did i mess up??


Solution

  • The immediate problem is

    less=`expr %rn - 1`
    

    Change that to

    less=`expr $rn - 1`
    

    and you should sail home. But you can also debug your scripts using the -x option of bash which would give you a line by line analysis.

    The use of expr is discouraged as you could easily replace that with ((expression)) construct (or calc if you need floating point operations). Then,

    fact=`expr $rn \* $less`
    

    will become a much easier

    ((fact=rn*less))
    

    The advantage is that you should not bother escaping characters that have special meanings in shell like *