How to calculate the sum of digits of a number n entered by user

 

Linux Bash Script

echo "Input the number: whose sum of digits need to be calculated"
read num
while [[ $num -gt 0 ]]
do
        let temp=$num%10
        let sum=$sum+$temp
        let num=$num/10
done
echo "Sum of Digits: $sum"

 

Execute the Linux Script

./6_sum_of_digits.sh

 

Output of Linux Script

Input the number: whose sum of digits need to be calculated
4956
Sum of Digits: 24