simple? sh problen
Ian Smith
smithi at nimnet.asn.au
Sun May 15 14:43:07 PDT 2005
On Sun, 15 May 2005, Mikko Työläjärvi wrote:
> On Mon, 16 May 2005, Ian Smith wrote:
> > How do I test whether a sh argument is an integer or not, so as to avoid
> > failing on a syntax error from otherwise working code such as:
> >
> > [ $3 -lt 10 -o $3 -gt 600 ] && echo "$0 $1 $2: $3 invalid" && exit 1
> >
> > when $3 is a non-integer argument? Do I need to delve into awk and REs,
> > or is there something more simple I've missed in mans test, expr, etc?
>
> Here are some suggestions for functions to do the test:
>
> isnum() {
> expr "$1" : '^[0-9][0-9]*$' >/dev/null
> }
>
> isnum() {
> case "$1" in
> *[^0-9]*|'') return 1;;
> esac
> return 0
> }
>
> The second one is likely to be faster unless "expr" is a shell builtin
> (typically it it not).
Thanks Mikko; I liked the look of the case version, and it works fine:
if ! isnum $3; then echo "$0 $1 $2: $3 is not an integer"; exit 1; fi
> $.02,
Worth every penny. Cheers, Ian
More information about the freebsd-questions
mailing list