0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Count Digits in a Number

Use echo -n "$number" | wc -c in Bash to count the digits of a number stored in the variable number.
📋

Examples

Input12345
Output5
Input007
Output3
Input0
Output1
🧠

How to Think About It

To count digits in a number, treat the number as a string and count how many characters it has. This works because each digit is one character. We ignore any non-digit characters by assuming input is a clean number.
📐

Algorithm

1
Get the input number as a string.
2
Count the number of characters in the string.
3
Return the count as the number of digits.
💻

Code

bash
#!/bin/bash
read -p "Enter a number: " number
count=$(echo -n "$number" | wc -c)
echo "Number of digits: $count"
Output
Enter a number: 12345 Number of digits: 5
🔍

Dry Run

Let's trace the input '12345' through the code

1

Input read

User inputs '12345', stored in variable number='12345'

2

Count digits

echo -n "$number" | wc -c counts characters: 5

3

Output result

Prints 'Number of digits: 5'

StepVariableValue
1number12345
2count5
3outputNumber of digits: 5
💡

Why This Works

Step 1: Treat number as string

The input number is handled as a string so we can count characters easily.

Step 2: Count characters

Using wc -c counts the number of characters, which equals digits.

Step 3: Print result

The script outputs the count as the number of digits.

🔄

Alternative Approaches

Using parameter expansion
bash
#!/bin/bash
read -p "Enter a number: " number
count=${#number}
echo "Number of digits: $count"
This method uses Bash's built-in string length feature, which is faster and simpler.
Using arithmetic loop
bash
#!/bin/bash
read -p "Enter a number: " number
count=0
while [ $number -ne 0 ]; do
  number=$((number / 10))
  ((count++))
done
echo "Number of digits: $count"
This method counts digits by dividing the number repeatedly; it only works for positive integers.

Complexity: O(n) time, O(1) space

Time Complexity

Counting characters requires scanning each character once, so time is proportional to the number of digits, O(n).

Space Complexity

Only a few variables are used, so space complexity is constant, O(1).

Which Approach is Fastest?

Using Bash parameter expansion ${#variable} is fastest as it avoids external commands like wc.

ApproachTimeSpaceBest For
Using wc -cO(n)O(1)Simple scripts, any Bash version
Using ${#variable}O(n)O(1)Fastest, pure Bash, no external calls
Arithmetic loopO(digits)O(1)Only positive integers, slower
💡
Use Bash's built-in ${#variable} to get string length quickly without external commands.
⚠️
Counting digits by treating the number as an integer can fail for numbers with leading zeros or non-integers.