.sh check for numeric content
Karl Vogel
vogelke+unix at pobox.com
Thu Jun 24 03:46:58 UTC 2010
>> On Thu, 24 Jun 2010 09:24:39 +0800,
>> Aiza <aiza21 at comclark.com> said:
A> Receiving a variable from the command line that is suppose to contain
A> numeric values. How do I code a test to verify the content is numeric?
The script below will work with the Bourne or Korn shell.
Results for "0 1 12 1234 .12 1.234 12.3 1a a1":
0 is numeric
1 is numeric
12 is numeric
1234 is numeric
.12 is numeric
1.234 is numeric
12.3 is numeric
1a is NOT numeric
a1 is NOT numeric
--
Karl Vogel I don't speak for the USAF or my company
I place economy among the first and most important virtues, and public debt
as the greatest of dangers to be feared. To preserve our independence, we
must not let our rulers load us with perpetual debt. --Thomas Jefferson
---------------------------------------------------------------------------
#!/bin/sh
# Test an argument to see if it's numeric. Handles decimals, but
# a minus sign in the regex will throw an error: "expr: illegal option".
PATH=/bin:/usr/bin:/usr/local/bin
export PATH
case "$#" in
0) echo need an argument. ; exit 1 ;;
*) ;;
esac
for arg
do
if expr "$arg" : "[0-9]*[\.0-9]*$" > /dev/null
then
echo "$arg is numeric"
else
echo "$arg is NOT numeric"
fi
done
exit 0
More information about the freebsd-questions
mailing list