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

#!/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"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
6 comments… add one
  • blandit Nov 27, 2011 @ 4:24

    what the mean $(( $n / 10 )) or $(( $n % 10 ))???

  • lej Aug 11, 2009 @ 11:05

    hi,pls.answer

  • lej Aug 11, 2009 @ 11:04

    what will you get if you add 2 odds numbers and an even number?

  • Evan Stratford Feb 9, 2009 @ 18:39

    What if n is zero?

  • DustyDingo Jan 18, 2009 @ 21:32

    Hi,
    num=`printf “%d” 42` && echo ${#num}

    • arshida Dec 25, 2010 @ 15:30

      can u pls say a Source code for sum of two no’s

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.