Shell Script to Print the Sum of Digits of a Number

shell script is a computer program designed to be run by the Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script that sets up the environment, runs the program, and does any necessary cleanup, logging, etc. is called a wrapper.

In this post, we will write a shell script to accept a number and print the sum of digits.

INPUT:
line 1: number

OUTPUT:
line 1: sum of digits

The following is the shell script to accept a number and print the sum of digits:

echo enter n
read n
sum=0
while [ $n -gt 0 ]
do
r=$(expr $n % 10)
sum=$(expr $sum + $r)
n=$(expr $n / 10)
done
echo sum is $sum

OUTPUT:

$ enter n
$ 456
$ sum is 15

Let us know in the comments if you are having any questions regarding this shell script.

And if you found this post helpful, then please help us by sharing this post with your friends. Thank You

Leave a Reply