Calvin
Calvin

Reputation: 309

Shell Script: How do I add the digits of a number?

I am making a shell script that takes a single number (length is unimportant) from the command line and adds the digits of it together. I thought I had it, but it won't work and either displays "0+3+4+5" if the command input is 345 or it displays the variables when I use expr to add them.

#!/bin/bash
sum=0
i="$(expr length $1)"
s=$1

for i in $(seq 0 $((${#s} - 1))); do
    value=${s:$i:1}
    typeset -i value
    sum=$sum+$value
done
echo $sum

Also doesn't work when I replace it with sum='expr $sum + $value'

any ideas?

Upvotes: 1

Views: 1410

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263197

#!/bin/bash

expr $(echo $1| sed 's/./& + /g;s/..$//')

For example, if the argument is 12345, this translates it to the string 1 + 2 + 3 + 4 + 5 and uses expr to evaluate it.

Upvotes: 0

dragonroot
dragonroot

Reputation: 5821

What you are looking for is sum=$(($sum+$value)).

Upvotes: 4

Related Questions