0

This is a homework I have for my Operative Systems class... This program sums all the digits from a number and returns the sum e.g. 123 1+2+3 = 6 I have an error in the for statement, but I don't know what I'm doing wrong... please help!

#!/bin/sh
read number
len=${#number}
cont=0
for(( i = 0 ; i < $len; i++ )) 
do
     cont=expr `$cont + number%10`
     number=`$number / 10`
done
echo "$cont"

Terminal gives me the error ./ej.sh: 5: Syntax error: Bad for loop variable

2
  • 1
    What version of bash? did you try using #!/bin/bash ? Commented Aug 26, 2011 at 0:28
  • Shell languages are very sensitive to whitespace. Don't forget, you are executing commands, not C-ish functions. Commented Aug 26, 2011 at 1:01

2 Answers 2

1

1) write the shebang as /bin/bash

2) you don't need the dollar sign in the expression

3) you should wrap the entire expr in backticks

#!/bin/bash
read number
len=${#number}
cont=0
for (( i = 0 ; i < len; i++ )); do
     cont=`expr $cont + $number % 10`
     number=`expr $number / 10`
done
echo "$cont"
Sign up to request clarification or add additional context in comments.

3 Comments

Good idea to use $() instead of backticks: easier to nest, and easier to see.
don't even need the expr :)
@ghostdog74, yes, you can do something like ((cont=cont + number % 10)). I merely wanted to highlight the key issues with the original code
0

You did not mention whether its purely bash or not..

$ echo "1234"|sed 's/\(.\)/\1+/g;s/\+$//' | bc
10

Comments

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.