Shell - Test a numeric variable

June 2017



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


Published by deri58. Latest update on December 10, 2012 at 11:24 AM by deri58.
This document, titled "Shell - Test a numeric variable," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).