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.
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.
Note: In the following example, the "[ [:digit:] ]" expression should be written without spaces between double brackets.
if [ "$(echo $var | grep "^[ [:digit:] ]*$")" ]
echo "the string ins numeric"
Based on the return code (here in the $statut variable) after a test on an arithmetic operation using the "expr" command .
expr $var + 0 1>/dev/null 2>&1
if test $statut -lt 2
echo "$var" numeric
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.
[ $var -eq 0 ] 2> /dev/null
if [ $? -eq 0 -o $? -eq 1 ]
echo "The string is numeric"
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:
if let $var 2>/dev/null
echo "$var numeric"
echo "$var not numeric"
Note that the line "if let $var 2>/dev/null" can also be written as: