This is a homework I have for my Operative Systems class... This program sums 开发者_Go百科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
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"
You did not mention whether its purely bash
or not..
$ echo "1234"|sed 's/\(.\)/\1+/g;s/\+$//' | bc
10
精彩评论