0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Check if String is Numeric

Use [[ "$string" =~ ^[0-9]+$ ]] in Bash to check if a string contains only digits and is numeric.
📋

Examples

Input12345
OutputNumeric
Inputabc123
OutputNot numeric
Input
OutputNot numeric
🧠

How to Think About It

To check if a string is numeric, think about verifying if every character is a digit from 0 to 9. We can use a pattern that matches only digits from start to end. If the string matches this pattern, it is numeric; otherwise, it is not.
📐

Algorithm

1
Get the input string.
2
Check if the string matches the pattern of digits only.
3
If it matches, return that it is numeric.
4
Otherwise, return that it is not numeric.
💻

Code

bash
#!/bin/bash

read -p "Enter a string: " string

if [[ "$string" =~ ^[0-9]+$ ]]; then
  echo "Numeric"
else
  echo "Not numeric"
fi
Output
Enter a string: 12345 Numeric
🔍

Dry Run

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

1

Input string

string = '12345'

2

Regex check

'12345' matches ^[0-9]+$ (only digits)

3

Output result

Print 'Numeric'

StepStringRegex MatchOutput
112345YesNumeric
💡

Why This Works

Step 1: Regex pattern

The pattern ^[0-9]+$ means the string must start (^) and end ($) with one or more (+) digits (0-9).

Step 2: Bash conditional

The [[ ... ]] test evaluates if the string matches the regex pattern.

Step 3: Output decision

If the test passes, the script prints 'Numeric'; otherwise, it prints 'Not numeric'.

🔄

Alternative Approaches

Using expr command
bash
#!/bin/bash
read -p "Enter a string: " string
if expr "$string" : '^[0-9][0-9]*$' >/dev/null; then
  echo "Numeric"
else
  echo "Not numeric"
fi
Uses external expr command; less efficient but works on older shells.
Using grep
bash
#!/bin/bash
read -p "Enter a string: " string
if echo "$string" | grep -qE '^[0-9]+$'; then
  echo "Numeric"
else
  echo "Not numeric"
fi
Uses grep command; useful if regex support in [[ ]] is limited.

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

Time Complexity

The regex check scans each character once, so it runs in linear time relative to string length.

Space Complexity

The check uses constant extra space, only storing the input string and temporary variables.

Which Approach is Fastest?

Using Bash's built-in regex with [[ ]] is fastest and most efficient compared to external commands like expr or grep.

ApproachTimeSpaceBest For
Bash [[ regex ]]O(n)O(1)Simple, fast, modern scripts
expr commandO(n)O(1)Older shells, compatibility
grep commandO(n)O(1)When regex in [[ ]] is unsupported
💡
Use double brackets [[ ]] with regex for a simple and efficient numeric check in Bash.
⚠️
Forgetting to anchor the regex with ^ and $ causes partial matches and incorrect results.