.sh check for numeric content
Anonymous
swell.k at gmail.com
Sun Jun 27 07:48:48 UTC 2010
Giorgos Keramidas <keramida at ceid.upatras.gr> writes:
> On Thu, 24 Jun 2010 05:19:53 +0200, Thomas Keusch <fwd at bsd-solutions-duesseldorf.de> wrote:
>> tk at eternity:~$ b=5
>> tk at eternity:~$ case "$b" in
>>> [0-9] )
>>> echo numeric
>>> ;;
>>> * )
>>> echo alpha
>>> ;;
>>> esac
>> numeric
>> tk at eternity:~$
>>
>> Works for me.
>
> Depending on what "numeric" means, this may be ok. For other numeric
> values (e.g. floating point numbers) There are simple, fast and correct
> ways to check but you have to escape from the shell, e.g.:
>
> $ var=3.1415926535897931
> $ python -c "$var + 0.0" >/dev/null 2>&1 ; echo $?
> 0
$ printf %g $var 2>&- >&- ; echo $?
0
>
> $ var=3a.1415926535897931
> $ python -c "$var + 0.0" >/dev/null 2>&1 ; echo $?
> 1
$ printf %g $var 2>&- >&- ; echo $?
1
It also understands %e and %a -notation, e.g. 3.14e+2 and 0x1.3ap+8.
$ python -c 0x1.3ap+8 2>&- >&- ; echo $?
1
$ printf %g 0x1.3ap+8 2>&- >&- ; echo $?
0
>
> The overhead of spawning a full-blown language interpreter like Perl or
> Python may be acceptable if you have to check "a few" values. Then it
> may be overkill if you want to check a million values. It's really up
> to you, as a programmer, to pick the right method.
Besides, printf(1) is also builtin in some shells which can reduce
overhead of spawning process. IIRC, there is some support for builtin
printf in our /bin/sh but it's disabled.
More information about the freebsd-questions
mailing list