Your error is caused by the spaces surrounding the =
in the assignments, the following replacements should work (I prefer $()
to using backticks since they're much easier to nest):
s=0
r=$(expr $a % 10)
s=$(expr $s + $r)
a=$(expr $a / 10)
For example, s = 0
(with the spaces) does not set the variable s
to zero, rather it tries to run the command s
with the two arguments, =
and 0
.
However, it's not really necessary to call the external expr
1 to do mathematical manipulation and capture the output to a variable. That's because bash
itself can do this well enough without resorting to output capture (see ARITHMETIC EVALUATION
in the bash
man page):
#!/bin/bash
clear
read -p "Enter a number: " number
((sum = 0))
while [[ $number -gt 0 ]]; do
((sum += number % 10))
((number /= 10))
done
echo "Sum of digits is $sum"
You'll notice I've made some other minor changes which I believe enhances the readability, but you could revert back to the your original code if you wish and just use the ((expression))
method rather than expr
.
1 If you don't mind calling external executables, there's no need for a loop in bash
, you could instead use sneakier methods:
#!/bin/bash
clear
read -p "Enter a number: " number
echo "Sum of digits is $(grep -o . <<<$number | paste -sd+ | bc)"
But, to be brutally honest, I think I prefer the readable solution :-)