简体   繁体   中英

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?

你要找的是sum=$(($sum+$value))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM