Shell program to read a number and find the sum of digits

by on April 8, 2008 · 9 comments

  1. #!/bin/bash
  2. # Shell program to read a number and find the sum of digits
  3. # -----------------------------------------------
  4. # Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # -------------------------------------------------------------------------
  7. # This script is part of nixCraft shell script collection (NSSC)
  8. # Visit http://bash.cyberciti.biz/ for more information.
  9. # -------------------------------------------------------------------------
  10.  
  11. echo -n "Enter number : "
  12. read n
  13.  
  14. # store single digit
  15. sd=0
  16.  
  17. # store number of digit
  18. sum=0
  19.  
  20. # use while loop to caclulate the sum of all digits
  21. while [ $n -gt 0 ]
  22. do
  23. sd=$(( $n % 10 )) # get Remainder
  24. n=$(( $n / 10 )) # get next digit
  25. sum=$(( $sum + $sd )) # calculate sum of digit
  26. done
  27. echo "Sum of all digit is $sum"
  28.  


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • basant kumar

    please provide more shell script for unix reader..

  • jadu saikia

    A one liner for sum of digits using sed.

    $ expr $(echo "12334" | sed 's/[0-9]/ + &/g' | sed 's/^ +//g')

    13

  • ruchika

    a shell script to calculate the sum of digits of a 5 digit number which is input through the keyboard

  • ruchika

    shell script that reads a filename from the command line and changes the name to filename.aa.where aa is the logname of the user

  • Poo

    Can any1 temme how to do shell program to find the sum of digits of a number until a single digit is obtained ?

  • kalpana

    is this the shell program to find the sum of digits of a number until a single digit is obtained?

  • mahsa

    please write shell script to find sum of first $ last digit of number

  • ShanthaKumar

    very late, but here is it ;)

    $ read a && echo $(echo $a | grep -o . | head -1) + $(echo $a | grep -o . | tail -1) |bc

  • ShanthaKumar

    echo -n “Sum of the digits is ” && echo $( echo $1 | grep -o . | tr “n” “+” && echo “0″) | bc

Previous Script:

Next Script: