Bash Scripting
Variable Testing
Programming
Coding Knowledge
Shell Scripts

How do I test if a variable is a number in Bash?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Bash scripting, checking whether a variable is a number is a common task that can be essential for validating user inputs, ensuring the correctness of arithmetic operations, or managing data correctly within scripts. This article will detail various methods to test if a variable contains a numeric value in Bash, complete with technical explanations and examples.

Method 1: Using Regular Expressions

Bash provides built-in support for regular expressions, which can be very handy for this purpose. To determine if a variable is a number, you can use a regex that matches numbers. Here's an example:

bash
1is_number_regex='^-?[0-9]+([.][0-9]+)?$'
2
3variable="123"
4if [[ $variable =~ $is_number_regex ]]
5then
6    echo "The variable is a number."
7else
8    echo "The variable is not a number."
9fi

This script checks if the variable is a whole number or a decimal. The regex expression ^-?[0-9]+([.][0-9]+)?$ works as follows:

  • ^-? allows for an optional negative sign.
  • [0-9]+ ensures there is at least one digit.
  • ([.][0-9]+)? allows an optional decimal point followed by one or more digits.

Method 2: Using declare and Arithmetic Evaluation

Another way is to use declare -i to treat a variable as an integer. Bash will automatically convert any value assigned to such a variable to an integer, or give an error if the value is not numerical. This can be combined with arithmetic evaluation:

bash
1variable="123a"
2declare -i test_variable
3test_variable=$variable 2>/dev/null
4
5if [ $? -eq 0 ]; then
6    echo "The variable is a number."
7else
8    echo "The variable is not a number."
9fi

In this method, trying to assign a non-numeric value to test_variable generates an error, which is silenced by 2>/dev/null. The special variable $? holds the exit status of the last command (0 indicates success).

Method 3: Using expr

expr is an external utility to evaluate expressions. It can be used to check if a variable is numeric by attempting an arithmetic operation with it:

bash
1variable="123"
2if expr "$variable" + 1 &>/dev/null; then
3    echo "The variable is a number."
4else
5    echo "The variable is not a number."
6fi

Here, expr "$variable" + 1will succeed only if$``variable is numeric. The output and errors are redirected to /dev/null.

Summary Table

MethodAdvantageDisadvantage
Regular ExpressionAccurate for floating and integersSlightly complex syntax
declare -iSimple and cleanOnly for integers, does not handle decimals
exprUses external utility, general approachMight be slower, error handling by redirection

Additional Considerations

  1. Handling Edge Cases: Always consider testing variables that may have leading zeros, signs, or unusual formats like hexadecimal.
  2. Performance: For scripts where performance is critical, native Bash options like regex might be preferable over external commands like expr.
  3. Readability: Choose the method that offers the best readability and maintainability for your script's context.

By selecting the appropriate technique based on the specific requirements and constraints of your Bash script, you can effectively determine if a variable is a number, thereby enhancing the robustness and reliability of your Bash scripts.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.