0

I'm trying to write sum of digits of an integer in shell but i have come across an error which is something like this "scriptprog5.sh: line 4: [: : integer expression expected"..

My code is:

read n  
sd=0  
sum=0  
while [ "$n" -gt 0 ]
do  
sd=`expr $n % 10`  
sum=`expr $sum + $sd`  
n=`expr $n / 10`  
done  
echo "Sum of digit for given number is $sum"

Please help...

  • 1
    Work fine with `sh` for me. Probably, you entered a non-numeric or empty input. Check that the input value is a valid integer before going ahead with the rest of the logic. – codeforester Mar 04 '18 at 06:17
  • This post may help you: https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash – codeforester Mar 04 '18 at 06:23
  • Worked fine for me as well with sh. As suggested by @codeforester you might have entered non-numeric or empty input. I got the same error as yours when I entered a non-numeric input. – Srikanth N Mar 05 '18 at 05:58
  • Possible duplicate of [Bash error: Integer expression expected](https://stackoverflow.com/questions/30140228/bash-error-integer-expression-expected) – tripleee Mar 26 '19 at 14:12

0 Answers0