loader image

Shell script to find sum of digits

Aim : Write a shell script to find sum of all digits from a given number

#!/bin/bash
echo "Enter a Number:"
read n
temp=$n
sd=0
sum=0
while [ $n -gt 0 ]
do
sd=$(( $n % 10 ))
n=$(( $n / 10 ))
sum=$(( $sum + $sd ))
done
echo "Sum is $sum"
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
MisterlastDark

#!/bin/bash

# Check if a number is passed as an argument
if [ -z “$1” ]; then
  echo “Please provide a number.”
  exit 1
fi

# Convert the number to a string
number_str=$1

# Calculate the sum of all digits
sum=0
for ((i=0; i<${#number_str}; i++)); do
  digit=${number_str:$i:1}
  let “sum += digit”
done

echo “The sum of all digits in $1 is $sum.”

Scroll to Top