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

Re: test if a parameter is numeric

----- Original Message ----- From: "Bart Schaefer" <schaefer@xxxxxxxxxxxxxxxx>
To: <zsh-users@xxxxxxxxxx>
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.
   unset N
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: Reverse Date, Date, Thread, Author