summaryrefslogtreecommitdiff
path: root/examples/functions/isnum.bash
blob: b733965782dbcc5b319499f1b9b32e7242120e4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#From: jrmartin@rainey.blueneptune.com (James R. Martin)
#Newsgroups: comp.unix.shell
#Subject: Re: testing user input on numeric or character value
#Date: 26 Nov 1997 01:28:43 GMT

# isnum returns True if its argument is a valid number,
# and False (retval=1) if it is any other string.
# The first pattern requires a digit before the decimal
# point, and the second after the decimal point.

# BASH NOTE: make sure you have executed `shopt -s extglob' before
# trying to use this function, or it will not work

isnum() # string
{
    case $1 in
    ?([-+])+([0-9])?(.)*([0-9])?([Ee]?([-+])+([0-9])) )
        return 0;;
    ?([-+])*([0-9])?(.)+([0-9])?([Ee]?([-+])+([0-9])) )
        return 0;;
    *) return 1;;
    esac
}

isnum2() # string
{
    case $1 in
    ?([-+])+([[:digit:]])?(.)*([[:digit:]])?([Ee]?([-+])+([[:digit:]])) )
        return 0;;
    ?([-+])*([[:digit:]])?(.)+([[:digit:]])?([Ee]?([-+])+([[:digit:]])) )
        return 0;;
    *) return 1;;
    esac
}

isint() # string
{
    case $1 in
    ?([-+])+([0-9]) )
        return 0;;
    *) return 1;;
    esac
}

isint2() # string
{
    case $1 in
    ?([-+])+([[:digit:]]) )
        return 0;;
    *) return 1;;
    esac
}