Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
How do I find out if the arguments passed to a script are of the integer type. Not just one argument. It can be at least 3
Frank Cappuchio

I like to use expr for the numeric test. The easiest way to loop through your parameters is to shift them down, but of course that makes them disappear. In the following script, I first save the parameter list, then check them all, then set them back up with the set command.
#!/bin/sh
if [ $# -eq 0 ] ; then
echo 'Need at least one parameter'
exit 1
fiallparms=$*
k=0until [ $# -eq 0 ]
do
if expr "$1" : "[0-9]*$" > /dev/null ; then
echo "$1 (all digits)"
else
echo "$1 (NOT all digits)"
((k=k+1))
fi
shift
doneset $allparms
if [ $k -gt 0 ] ; then
echo "\nAt least one parameter was not all digits\n"
fiexit 0

James,
This is exactly what I want, now I need to be able to enter numbers such as:
-5 8
8 -10
0 0
-1 -4how can I modidy the script to accept this type of patterns. No other pattern will be valid.
Thanks a million.
Frank

The following tests for the first character being either a dash or digit, to be followed by zero or more digits:
if expr "X$1" : "X[-|0-9][0-9]*$" > /dev/null ; then
echo "$1 (valid)"
else
echo "$1 (NOT valid)"
((k=k+1))
fiThe X avoids confusion when the argument is a single character that would be taken as an operator such as dash or equal-sign (see man page).
A problem with the above is that it would show a single dash as valid. To insist that a dash be followed by at least one digit, we can use a compound expression:
if expr X$1 : "X-[0-9][0-9]*$" \
\| X$1 : "X[0-9]*$" > /dev/null ; then
echo "$1 (valid)"
else
echo "$1 (NOT valid)"
((k=k+1))
fiNow a single dash would not be a match, (although -0 would match).

![]() |
Unix Printing
|
using ftp in Korn Shell
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |