In Bash, it’s often necessary to verify whether a variable contains a numeric value. This can be useful when validating user input, processing data, or performing arithmetic operations. In this tutorial, we’ll explore different methods for testing if a variable is a number in Bash.
Using Regular Expressions
One approach is to use regular expressions (regex) to match the variable’s content against a pattern that represents a number. The regex ^[0-9]+$
matches any string consisting only of digits from start (^
) to end ($
). You can use this regex with the [[ ]]
conditional expression, like so:
re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]]; then
echo "error: Not a number" >&2; exit 1
fi
To match numbers with decimal points or signs, you can modify the regex accordingly. For example, ^[+-]?[0-9]+([.][0-9]+)?$
matches numbers with optional signs and decimal points.
Using Pattern Matching
Another approach is to use Bash’s pattern matching feature, which allows you to match a string against a pattern using the case
statement:
case $string in
''|*[!0-9]*) echo bad ;;
*) echo good ;;
esac
This method rejects empty strings and strings containing non-digits. However, it doesn’t handle negative or floating-point numbers out of the box.
Using Arithmetic Expansion
A more straightforward approach is to use Bash’s arithmetic expansion feature, which allows you to perform arithmetic operations on a variable. If the variable contains a non-numeric value, the operation will fail, and you can catch the error:
if [ -n "$var" ] && [ "$var" -eq "$var" ] 2>/dev/null; then
echo number
else
echo not a number
fi
This method uses the [ -eq ]
operator to compare the variable with itself. If the comparison succeeds, it means the variable contains a numeric value.
Tips and Caveats
When testing if a variable is a number in Bash, keep in mind:
- Regular expressions can be powerful but may not cover all edge cases.
- Pattern matching can be simpler but less flexible than regex.
- Arithmetic expansion can be concise but may not work as expected for non-Bash shells or certain input values.
In general, it’s essential to choose the method that best fits your use case and handle potential errors and edge cases accordingly.