Differences between revisions 30 and 32 (spanning 2 versions)
Revision 30 as of 2012-05-11 20:51:25
Size: 5804
Editor: e36freak
Comment: typo correction, incorrect variable name
Revision 32 as of 2012-12-02 02:34:38
Size: 4278
Editor: S01060048548a70fe
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
Line 16: Line 17:
Line 26: Line 26:
Line 35: Line 34:
Line 44: Line 42:
Line 58: Line 55:
Line 72: Line 68:
Line 78: Line 73:
regexp='^[-+]?[0-9]*(\.[0-9]*)?$'  regexp='^[-+]?[0-9]*(\.[0-9]*)?$'
Line 85: Line 80:
Line 87: Line 81:
Line 93: Line 86:
}}}   }}}
Line 98: Line 90:
Line 104: Line 97:
Line 107: Line 99:
=== Using the integer type ===

If you just want to guarantee ahead of time that a variable contains an integer, without actually checking, you can give the variable the "integer" attribute.
=== Using ((...)) to determine if input is integer ===
Line 112: Line 101:
# Bash
declare -i foo
foo=-10+1; echo "$foo" # prints -9

foo="hello"; echo "$foo"
# the value of the variable "hello" is evaluated; if unset, foo is 0

foo="Some random string" # results in an error.
if (("$foo")) >/dev/null 2>&1; then
  echo "$foo is an integer"
Line 121: Line 105:

Any value assigned to a variable with the integer attribute set is evaluated as an [[ArithmeticExpression|arithmetic expression]] just like inside `$(( ))`. Bash will raise an error if you try to assign an invalid arithmetic expression.

In Bash and ksh93, if a variable which has been declared integer is used in a `read` command, the user's input is treated as an [[ArithmeticExpression|arithmetic expression]], as with assignment. In particular, if the user types an identifier, the variable will be set to the value of the variable with that name, and `read` will give no other indication of a problem.

# Bash (and ksh93, if you replace declare with typeset)
$ declare -i foo
$ read foo
$ echo $foo # prints 0; 'hello' is unset, so is treated as 0 for arithmetic purposes
$ hello=5
$ read foo # user types hello again
$ echo $foo # prints 5, the value of 'hello' as an arithmetic expression

Pretty useless if you want to read only integers.

In the older Korn shell (ksh88), if a variable is declared integer and used in a `read` command, and the user types an invalid integer, the shell complains, the read command returns an error status, and the value of the variable is unchanged.

# ksh88
$ typeset -i foo
$ foo=42
$ read foo
ksh: hello: bad number
$ echo $?
$ echo $foo
the command (($foo)) tries to parse foo as an integer arithmetic expression, which returns a non-zero error code if foo is not an integer.

How can I tell whether a variable contains a valid number?

First, you have to define what you mean by "number". The most common case when people ask this seems to be "a non-negative integer, with no leading + sign". Or in other words, a string of all digits. Other times, people want to validate a floating-point input, with optional sign and optional decimal point.

Hand parsing

If you're validating a simple "string of digits", you can do it with a glob:

# Bash
if [[ $foo != *[!0-9]* ]]; then
    echo "'$foo' is strictly numeric"
    echo "'$foo' has a non-digit somewhere in it"

The same thing can be done in Korn and POSIX shells as well, using case:

# ksh, POSIX
case "$foo" in
    *[!0-9]*) echo "'$foo' has a non-digit somewhere in it" ;;
    *) echo "'$foo' is strictly numeric" ;;

If you need to allow a leading negative sign, or if want a valid floating-point number or something else more complex, then there are a few possible ways. Standard globs aren't expressive enough to do this, but we can use extended globs:

# Bash -- extended globs must be enabled.
# Check whether the variable is all digits.
shopt -s extglob
[[ $var == +([0-9]) ]]

A more complex case:

# Bash
shopt -s extglob
[[ $foo = *[0-9]* && $foo = ?([+-])*([0-9])?(.*([0-9])) ]] &&
  echo "foo is a floating-point number"

The leading test of $foo is to ensure that it contains at least one digit. The extended glob, by itself, would match the empty string, or a lone + or -, which may not be desirable behavior.

Korn shell has extended globs enabled by default, but lacks [[, so we must use case to do the glob-matching:

# Korn
case $foo in
    case $foo in
        ?([+-])*([0-9])?(.*([0-9]))) echo "foo is a number";;

Note that this uses the same extended glob as the Bash example before it; the third closing parenthesis at the end of it is actually part of the case syntax.

If your definition of "a valid number" is even more complex, or if you need a solution that works in legacy Bourne shells, you might prefer to use an external tool's regular expression syntax. Here is a portable version (explained in detail here), using egrep:

# Bourne
if echo "$foo" | egrep '^[-+]?([0-9]+\.?|[0-9]*\.[0-9]+)$' >/dev/null
    echo "'$foo' is a number"
    echo "'$foo' is not a number"

Bash version 3 and above have regular expression support in the [[ command. Due to bugs and changes in the implementation of the =~ feature throughout bash 3.x, we do not recommend using it, but people do it anyway, so we have to maintain this example (and keep restoring this warning, too, when people delete it):

# Bash
# Put the RE in a var for backward compatibility with versions <3.2
if [[ $foo = *[0-9]* && $foo =~ $regexp ]]; then
    echo "'$foo' looks rather like a number"
    echo "'$foo' doesn't look particularly numeric to me"

Using the parsing done by [ and printf (or "using eq")

# fails with ksh
if [ "$foo" -eq "$foo" ] 2>/dev/null;then
 echo "$foo is an integer"

[ parses the variable and interprets it as in integer because of the -eq. If the parsing succeds the test is trivially true; if it fails [ prints an error message that 2>/dev/null hides and sets a status different from 0. However this method fails if the shell is ksh, because ksh evaluates the variable as an arithmetic expression.

You can use a similar trick with printf:

if printf "%f" "$foo" >/dev/null 2>&1; then
  echo "$foo is a float"

You can use %d to parse an integer. Take care that the parsing might be (is supposed to be?) locale-dependent.

Using ((...)) to determine if input is integer

if (("$foo")) >/dev/null 2>&1; then
  echo "$foo is an integer"

the command (($foo)) tries to parse foo as an integer arithmetic expression, which returns a non-zero error code if foo is not an integer.

BashFAQ/054 (last edited 2022-04-19 05:23:33 by emanuele6)