Zsh Mailing List Archive
Messages sorted by:
Re: test if a parameter is numeric
- X-seq: zsh-users 11185
- From: "Brian K. White" <brian@xxxxxxxxx>
- To: <zsh-users@xxxxxxxxxx>
- Subject: Re: test if a parameter is numeric
- Date: Sat, 10 Feb 2007 13:13:57 -0500
- Mailing-list: contact zsh-users-help@xxxxxxxxxx; run by ezmlm
- Organization: Aljex Software
- References: <Xns98D2ADD16C100zzappergmailcom@xxxxxxxxxxx> <070209182939.ZM18654@xxxxxxxxxxxxxxxxxxxxxx>
----- Original Message -----
From: "Bart Schaefer" <schaefer@xxxxxxxxxxxxxxxx>
Sent: Friday, February 09, 2007 9:29 PM
Subject: Re: test if a parameter is numeric
On Feb 9, 5:05pm, zzapper wrote:
} I just want to test if a parameter is numeric
} if [[ "$1" == [0-9] ]]
if [[ "$1" = <-> ]]
This is a zsh-ism, so it's not cross-shell portable, but the pattern <->
matches any string having any number of digits and only digits.
ksh, legacy sco/sun/etc sh, bash etc...
I usually load the value into an integer typset variable,
sometimes testing the success/fail of the assignment itself:
typeset -i N="$1" 2>/dev/null && echo yes || echo no
sometimes just using the resulting variable, treating "" different than "0"
or the same as "0" depending on the situation
typeset -i N="$1" 2>/dev/null
or if your shell has built in arithmatic (zsh/kash/bash, not plain sh on
platforms where sh isn't really bash) instead of using a type defined
variable, using the common age old trick (in any language) of just
attempting an arithmatic operation, add 0 to the value.
if $1 was numeric the N will have it, else N will still be unset
Both of the above approaches partially handle floating points.
The string may have a non-numerc "." in it, say "4.5" and the test will come
out positive as numeric.
But, N will be "4" not 4.5 or 5
Depending on the source of the data, you may also want to run the string
through tr -d "," so that 4,500 becomes 4500 and is treated as numeric.
Now someone will pipe up with some exotic 3 character zsh syntax thats like
built-in sed on the fly instead of running a command like tr. "tr!! that's
so 80's" heh :)
Brian K. White -- brian@xxxxxxxxx -- http://www.aljex.com/bkw/
filePro BBx Linux SCO FreeBSD #callahans Satriani Filk!
Messages sorted by: