From: Stephane CHAZELAS on
2010-03-17, 02:56(-04), Wayne:
> Francis Moreau wrote:
>> On Mar 13, 8:48 am, Decare <dec...(a)yeah.net> wrote:
>>> Is there any to determine whether a string
>>> is a integer or not? For example,
>>>
>>
>> not sure which integer formats you want to support but:
>>
>> expr $s \* 0 2>&1 >/dev/null
>>
>> might do it.
>
> Many folk forget that expr has a powerful reg exp (BRE) match
> operator of ":":
>
> LC_ALL=C expr -- X"$ARG" : 'X[+-]\{0,1\}[[0-9]\{1,\}$' >/dev/null
>
> But the BRE syntax is ugly as is the necessary "--" and "X",

You shouldn't need the "--" once you have the "X".

> I prefer the more readable grep version:
>
> LC_ALL=C printf -- "$ARG" | grep -Exqe '(-|\+)?[0-9]+'

printf '%s\n' "$ARG"

or you'll have problems with $ARGs containing "\"s or "%"s.

And again, it may fail for $ARGs containing "\n".

> or the single process (but a bit uglier) awk version:
>
> LC_ALL=C awk 'BEGIN { exit !(ARGV[1] ~ /^[-+]?[0-9]+$/) }' "$ARG"
>
> Since some older system use "egrep" and not "grep -E", either
> the expr or awk versions are likely more portable.

Systems that don't have grep -E are likely not to support \{1,\}
either.

The case based solution:

case $ARG in
"" | *[!0-9+-]* | ?*[-+]* | [-+]) echo no;;
*) echo yes;;
esac

is probably the most portable.


--
Stéphane
From: bsh on
Decare <dec...(a)yeah.net> wrote:
> Is there any to determine whether a string
> is a integer or not?
> ...

For completeness: there was a function example to determine
if a string conformed to the format of an integer or floating
point number -- "isnum" I think was its name. The "default"
case would then be for your determination of a non-numeric
string. It was written by The Master himself, DGK, as part of
a function library that is a superset of code examples from
his two kornshell books. Perhaps then it can be found in "The
KornShell Command and Programming Language", 2nd edition",
insofar as the current link for "isnum" is dead!

http://kornshell.com/software/ # under "Examples" link

=Brian
From: bsh on
On Mar 23, 6:49 pm, bsh <brian_hi...(a)rocketmail.com> wrote:
> Decare <dec...(a)yeah.net> wrote:
> > ... determine whether a string is a integer or not?
> > ...
> ... Perhaps then it can be found in "The
> KornShell Command and Programming Language", 2nd edition",
> insofar as the current link for "isnum" is dead!

Ah, I should have first thought to search for any old
submissions of mine of this function code:

http://groups.google.com/group/comp.unix.shell/msg/6cedcd74623a99d5

=Brian