Shell program to calculate the number of digits in a number read from the user

in Categories Academic, Shell Math last updated April 8, 2008
#!/bin/bash
# Shell program to calculate the number of digits in a
# number read from the user
# -----------------------------------------------
# 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 number : "
read n
 
sd=0
 
# store number of digit 
nd=0
on=$n # store $n so that we can use it later
 
# use while loop to caclulate the number of digit
while [ $n -gt 0 ]
do
    sd=$(( $n % 10 )) # get Remainder 
    n=$(( $n / 10 )) 
    nd=$(( $nd + 1)) # calculate all digit in a number till n is not zero
done
echo  "Numnber of digit in a $on is $nd"

Share this on:

6 comment

    Have a question? Post it on our forum!