You are not logged in.

#1 2008-04-04 23:26:08

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

[BASH] Positive integer test

OK, all i need to do is have an input of purely digits (therefore a positive integer) be accepted, and anything else come out as an error.

Number 54 from here doesn't seem to work, as any letter seems to be accepted:

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

This works but also accepts negative numbers.

Is it really that hard to test for a positive integer, or am I missing something really simple?

Thanks.

Last edited by dyscoria (2008-04-04 23:26:55)


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

#2 2008-04-05 00:11:20

danielsoft
Member
From: Czech Republic
Registered: 2008-02-16
Posts: 102

Re: [BASH] Positive integer test

do you know regular expressions? this looks like a job for one of them:
try

 if [[ $foo =~ ^[0-9]+$ ]]

explanation:

=~ is the "regular expression match" operator
^ matches with beginning of string
[0-9] matches a digit
+ one or more of the previous (i.e. digit)
$ end of string


may the Source be with you

Offline

#3 2008-04-05 07:53:25

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

Re: [BASH] Positive integer test

That works like an absolute charm. Didn't know about the =~ operator.

Thanks bud!


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

Board footer

Powered by FluxBB