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

4
  • 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. Commented Mar 4, 2018 at 6:17
  • This post may help you: stackoverflow.com/questions/806906/… Commented Mar 4, 2018 at 6: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. Commented Mar 5, 2018 at 5:58
  • Possible duplicate of Bash error: Integer expression expected Commented Mar 26, 2019 at 14:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.