-1

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??

sjsam
  • 21,411
  • 5
  • 55
  • 102
Richi Dubey
  • 89
  • 12

1 Answers1

2

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 *

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • We also sometimes use variable name=$((expression)) .Does it work the same way as ((Entire thing))?? And why and where do we need to add spaces before variable for operations?? – Richi Dubey Jan 28 '18 at 06:09
  • @RichiDubey For the first part of your question, the answer is yes.. The `(())` construct automatically figure out the variables for you.. For assignments in bash, it is mandatory that there are no spaces before and after the `=` sign. I can't think of any other examples where the use of spaces are restricted. – sjsam Jan 28 '18 at 06:31