Peter Nosko wrote:
pn] Forgive me; I can't Google this for some reason.

pn] Is there an elegant way to test a positional parameter for being numeric (so that 
I don't
assign a string to a numeric variable)?

The quick & dirty way to do something like this would be with a case statement:


case $1
 in
  [0-9]*) echo Number: $1 ;;
  *) echo Text: $1 ;;
esac

Note that this only tests the *FIRST* character of the parameter, so something like 1a would incorrectly look like a number.

To get around this problem (if necessary), you'll either need to recursively parse each digit of the parameter to see if it's a number (ugly, but relies only on built-in shell commands)...something like:

<example>

#!/bin/ash

ParseChar () {
case $1
 in
  [0-9]*)
    if [ ${#1} -ge 2 ] ; then
      Parse ${1#?}
    fi ;;
  *) NUMBER=NO ;;
esac
}

Parse () {
  NUMBER=YES
  ParseChar $1
}

Parse $1

echo "Number?: $NUMBER"

</example>

...or pass the whole thing to something like sed that can deal with more complicated regular expressions.

NOTE: You could probably clean up the recursive example code. I'd probably try to get away from using the NUMBER global, and maybe pass the Parse procedure a second parameter containing the variable name you'd like the number or a default value assigned to, and you might want (or need) to deal with a leading +/- sign, a decimal (only one!) and/or comma seperators (ie -32,768.0), but the above does actually work for "plain" numbers.

--
Charles Steinkuehler
[EMAIL PROTECTED]




------------------------------------------------------- This SF.Net email sponsored by: Free pre-built ASP.NET sites including Data Reports, E-commerce, Portals, and Forums are available now. Download today and enter to win an XBOX or Visual Studio .NET. http://aspnet.click-url.com/go/psa00100006ave/direct;at.asp_061203_01/01 ------------------------------------------------------------------------ leaf-user mailing list: [EMAIL PROTECTED] https://lists.sourceforge.net/lists/listinfo/leaf-user SR FAQ: http://leaf-project.org/pub/doc/docmanager/docid_1891.html

Reply via email to