Shell - Test a numeric variable

December 2016



Introduction


In a "shell", the variables are in the "string" type (default). Does it imply that you can't declare a variable of the "integer" type?

Well, this is not quite true!

Examples of test


Here are three tests that making use of the following commands, coupled with some control instructions, such as the return code of a command.
  • grep
  • expr
  • test"


Note: In the below examples, we will assume that the $var variable is initialized according to the "$1" parameter, passed directly in the command line following the call of each script.

Using grep


Note: In the following example, the "[ [:digit:] ]" expression should be written without spaces between double brackets.

#!/bin/bash 
# script_grep.sh 

var=$1 
if [ "$(echo $var | grep "^[ [:digit:] ]*$")" ] 
then 
 echo "the string ins numeric" 
fi 

Using expr


Based on the return code (here in the $statut variable) after a test on an arithmetic operation using the "expr" command .
#!/bin/sh  
# script_expr.sh 

var=$1 
expr $var + 0 1>/dev/null 2>&1 
statut=$?  
if test $statut -lt 2  
then  
 echo "$var" numeric  
fi 

Using Test


Based on the use of the the "test" command (represented here "[" and "]"). Check if the value of the $va variable is zero (0), and then evaluates the return code ($?) for its two output states (true or false, i.e 0 or 1). In the case that the return code greater than 1, then the evaluation failed.
#!/bin/bash 
# script_test.sh 

var=$1 
[ $var -eq 0 ] 2> /dev/null 
if [ $? -eq 0 -o $? -eq 1 ] 
then 
 echo "The string is numeric" 
fi 

Variable of the integer type


You can also initialize a variable of the "integer" type through the "POSIX" shell.

TO create an variable of the integer type, first declare it with the "typeset -i" or "let" command.
Here is an example that implements the use of the "let" command:

#!/bin/sh 
# script_let.sh 

var=$1 

if let $var 2>/dev/null  
then 
 echo "$var numeric" 
else 
 echo "$var not numeric" 
fi 

Note that the line "if let $var 2>/dev/null" can also be written as:
  • if let var 2>/dev/null

or
  • if ((var)) 2>/dev/null


Related :

This document entitled « Shell - Test a numeric variable » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.