Bash Script to Check if String is Alphabetic
Use
[[ $string =~ ^[a-zA-Z]+$ ]] in Bash to check if a string is alphabetic; it returns true if the string contains only letters.Examples
InputHelloWorld
OutputAlphabetic
InputHello123
OutputNot alphabetic
Input
OutputNot alphabetic
How to Think About It
To check if a string is alphabetic, think about verifying each character is a letter from A to Z or a to z. If all characters fit this rule and the string is not empty, then the string is alphabetic.
Algorithm
1
Get the input string.2
Check if the string matches the pattern of only letters (a-z, A-Z).3
If it matches, return that the string is alphabetic.4
Otherwise, return that it is not alphabetic.Code
bash
#!/bin/bash read -p "Enter a string: " string if [[ $string =~ ^[a-zA-Z]+$ ]]; then echo "Alphabetic" else echo "Not alphabetic" fi
Output
Enter a string: HelloWorld
Alphabetic
Dry Run
Let's trace the input 'Hello123' through the code
1
Input string
string = 'Hello123'
2
Pattern check
'Hello123' matches ^[a-zA-Z]+$ ? No
3
Output result
Print 'Not alphabetic'
| Input String | Regex Match | Output |
|---|---|---|
| HelloWorld | Yes | Alphabetic |
| Hello123 | No | Not alphabetic |
| No | Not alphabetic |
Why This Works
Step 1: Regex pattern
The pattern ^[a-zA-Z]+$ means the string must start and end with one or more letters only.
Step 2: Using [[ ]]
The Bash [[ ]] test allows regex matching with =~ operator.
Step 3: Conditional output
If the string matches, print 'Alphabetic'; otherwise, print 'Not alphabetic'.
Alternative Approaches
Using grep
bash
read -p "Enter a string: " string echo "$string" | grep -qE '^[a-zA-Z]+$' && echo "Alphabetic" || echo "Not alphabetic"
Uses external grep command; slightly slower but works in older shells.
Using case statement
bash
read -p "Enter a string: " string case "$string" in (*[!a-zA-Z]*) echo "Not alphabetic";; (*) echo "Alphabetic";; esac
Uses shell pattern matching; simple and portable.
Complexity: O(n) time, O(1) space
Time Complexity
The regex check scans each character once, so time grows linearly with string length.
Space Complexity
No extra memory is needed besides the input string; the check is done in-place.
Which Approach is Fastest?
The built-in Bash regex [[ =~ ]] is fastest; grep calls an external process, and case uses shell pattern matching which is also efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash regex [[ =~ ]] | O(n) | O(1) | Modern Bash scripts |
| grep command | O(n) | O(1) | Compatibility with older shells |
| case statement | O(n) | O(1) | Simple pattern matching without regex |
Use
[[ $string =~ ^[a-zA-Z]+$ ]] for a quick and clean alphabetic check in Bash.Forgetting to anchor the regex with
^ and $ causes partial matches and wrong results.