1

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?

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0
#!/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.

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.