Python, Perl, Tcl, and all UNIX shell scripting languages (like Bash) are examples of interpreted languages. This is the reason why Bash reads and interprets one command at a time and doesn’t segregate its variables by type. In fact, Bash is untyped.
In this tutorial, let’s go deeper and see how it’s possible to check if a variable is effectively a number. First, we’re going to show many possible solutions in detail. Second, we’ll explain the idea behind each solution.
2. Comparing Variables
Bash considers its variables as character strings, but it allows all arithmetical operations and comparisons on the variables. The basic idea is that to evaluate if a variable is a number, we need to verify that its value contains only digits.
2.1. Using Regular Expressions
As a first example, let’s write a script called integers.sh that uses a regular expression to make sure the given input is an integer value:
#!/bin/bash echo $1 | grep "^-\?[0-9]+$"
The main ingredients are:
- $1 contains the value of the parameter passed to the script invocation
- a regular expression is here defined after the grep command
More precisely, the Unix pipe provides the standard output of the first process (echo command) to the standard input of the second command (grep command). The accepted characters are numbers between 0 and 9. In addition to that, the sign along with the dashes states that we can use negative numbers.
If we want to define the regular expression for the positive numbers, we simply need to remove the dash sign only. So, let’s show two examples of the invocation of the previous script. Using an integer value, we have:
$ ./integers.sh 123 123
Otherwise, with a string, we get:
$ ./integers.sh cat
As we can see, the regular expression correctly accepts the integer value, and as expected, it rejects the word and doesn’t print it on the console.
2.2. Using the Equal Tilde Operator
Another way to solve the problem is using the Equal Tilde (=~) operator. This allows the use of the regular expressions in an if statement:
#!/bin/bash if ! [[ $1 =~ '^[0-9]+$' ]]; then echo "error: Not a number" >&2; exit 1 fi
The right side of the boolean condition is an extended regular expression. If the left side matches, the operator returns 0, and otherwise, it returns 1.
Let’s group these last instructions in a script called ext-regexp.sh and invoke it:
$ ./ext-regexp.sh 1
$ ./ext-regexp.sh a error: Not a number
This means that the script correctly ends with status 0 in case we use a number. Otherwise, it reports the error and exits with status 1.
2.3. Matching Real Numbers
We can simply change the matching rule for the regular expression to recognize the real numbers:
For the real numbers with the sign, we need to use:
In this tutorial, we’ve explained how to check if a variable is a number in Bash. The proposed solutions all rely on the use of regular expressions.