Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

test for integer

Status
Not open for further replies.

ReeKetta

Programmer
Aug 17, 2001
3
US
Is there a way to check to see if the user entered variable is a valid integer?

I have:

...
read var
if test $var -lt 5
then
echo "integer"
fi

This works just fine if var is an integer, but if it is not, then I get a "bad integer" error. I would like it to not give an error, if that is possible.

Thanks for the help.
 
This awk script may help... But is doesn't deal with exponents. It expects only the number (or one per line) and returns T or F.

BEGIN {
sign = "[+-]?"
integer = "[0-9]+"
ws = "[ ]*"
number = "^" ws sign integer ws "$"
}
{
printf ("%s\n", ($0 ~ number) ? "T" : "F")
}

Cheers,
ND [smile]
 
if on Solaris, "man ckstr"

Ex:

ckstr -Q -r "[-+]*[0-9][0-9]*[eE]*[-]*[0-9]*" -p "Input number: "
 

Using ksh try:

read n
if [ ! -n "$n" -o -n "$(echo $n | sed 's/[0-9]//g')" ]; then
echo "It is not a number"
else
echo "It is a number"
fi

Steve.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top