Shell script to read 5 digit number and calculate the sum of digit

in Categories Shell Math last updated April 4, 2008
#!/bin/bash
# Shell script to read 5 digit number and calculate the sum of digit
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter numnber : "
read n
 
# find out length of string using wc -c command
len=$(echo $n | wc -c)
 
# remove \n i.e. new line character
len=$(( $len - 1 ))
 
# use loop to go throug all digit one by one and calculate sum of digit on fly
for (( i=1; i <= $len; i++ ))
do
   sum=$(( $sum + $(echo $n | cut -c $i) ))
done
echo "Sum of $n is $sum"