Ignacio Pochart
Ignacio Pochart

Reputation: 129

for loop in shell

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

Upvotes: 0

Views: 1415

Answers (2)

ghostdog74
ghostdog74

Reputation: 342819

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

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

Upvotes: 0

Foo Bah
Foo Bah

Reputation: 26281

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"

Upvotes: 1

Related Questions