To use this type of function, you need a conditional expression version [[ ... ]] . [ is the "old" test command and does not process regular expressions at all.
#! /bin/bash function checkNumber { regExp='^[+-]?([0-9]+\.?|[0-9]*\.[0-9]+)$' if [[ $testNo =~ $regExp ]] then echo "That is a number!" let check=1 else echo "Damn! Not A Number!" fi } testNo=1 checkNumber testNo=-1.2 checkNumber testNo=+.2 checkNumber testNo=+0. checkNumber testNo=a checkNumber testNo=hello2you checkNumber $ ./t.sh That is a number! That is a number! That is a number! That is a number! Damn! Not A Number! Damn! Not A Number!
See What is the difference between the test, [and [[? .
Regular expression explanation:
^ Anchor at start of string $ Anchor at end of string
These two make regular expressions match the entire string passed; partial matches are not allowed.
[+-]
matches either + or - .
[+-]?
makes this part optional, so the above matches exactly + , - or nothing at all.
Then there is an alternation (part1|part2) that will match if part1 or part2 part1 .
Part one:
[0-9]+\.?
which corresponds to one or more ( + ) digits (but not zero digits / empty sets) and optional . . This processes numbers of the form 123 and 534. .. But not only that . .
The second part of:
[0-9]*\.[0-9]+
This corresponds to zero or more ( * ) digits, and then . followed by one or more digits. This corresponds to all other floats, such as 1.3 or .543 (without exponential notation), but still excludes only . .
source share