Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: test if a parameter is numeric



DervishD <zsh@xxxxxxxxxxxx>:
> Lydgate <zsh@xxxxxxxxxxxxxxxxxx> dixit:
> > On Sun, Feb 11, 2007 at 02:08:40AM +0100, DervishD wrote:
> > >     If you can use "expr", you can do it with "expr", using simple
> > > regexes. OK, not the fastest method, but should do and should do it
> > > pretty fast. I use this approach in my "mobs" project. Being bulletproof
> > > using almost-portable shell scripting is, at least, tricky. And probably
> > > impossible, for what I've seen...
> > 
> > Sorry maybe I'm missing something, but if you need to match more than
> > one digit, what's wrong with:
> > 
> > [[ "$1" == [0-9][0-9]* ]]
> > 
> > Which I think is more portable?
> 
>     If you are considering the second part as a regex, then the above is
> definitely NON portable. It's not even POSIX.
[...]
>     And the "[[" is NOT portable, either, it's a zsh thing (and probably
> bash has too, I don't know, but AFAIK is not POSIX/SuS).

"[[" was introduced by ksh, AFAIK.
And you are right, it's not SUSv3.
To check whether a variable contains only digits, how about this:

[snip]
if [ -n "${var}" ] && [ "${var}" = "${var%%[!0-9]*}" ] ; then
  echo "\$var holds a numeric value"
fi
[snap]

This should work in all shells that support SUSv3 syntax. It will
break in original bourne-type shells (like /bin/sh in opensolaris,
IIRC), because they do not understand ${var%%pattern} and the like.

Regards, Frank

-- 
In protocol design, perfection has been reached not when there is
nothing left to add, but when there is nothing left to take away.
                                                  -- RFC 1925



Messages sorted by: Reverse Date, Date, Thread, Author