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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Test for numerals

Status
Not open for further replies.

ravioli

Programmer
Mar 30, 2004
39
US
Hi All,

I am having a little trouble with a Shell script I am writing. I would like to test input to see if it contains only numerals. I have already checked it for length, between 3 and 8 characters long. Let's say the the variable is called $value, how would I write the if statement?

if [ $value -eq +([0-9]) ] ; then
echo "The input contains only numerals"
fi

I grabbed the +([0-9]) from a historical forum posting, but it didn't quite work in this form. Does anyone know the answer. I think I might be close.

Cheers, Ravioli
 
My script replaces everything not a number with nothing.
Than compares result with original value.

numbertest.sh
Code:
#!/bin/bash
STRIPPED=`echo $1 | sed 's/[^0-9]//g'`
if [[ $1 == $STRIPPED ]] 
then
	echo "number"
else
	echo "contaminated!"
fi
[code]

sed:
s/ substitute
[] something of a group
[0-9] something between 0 and 9
[^0-9] invers, something not between 0 and 9
// substitute with nothing
/g substitute not only once, but globally.
 
This type of globbing '?()' is only available with ksh, the correct syntax for the test is :

[tt] if [[ "$value" = +([0-9]) ]] ; then[/tt]

With all shells you can do :

[tt] if expr "$value" : '[0-9]\+$' >/dev/null ; then[/tt]

Jean Pierre.
 
Thank you stefan and aigles. I was using Korn so I tried to refine my code as in the aigles example. I can see this should work. But after much trying and frustration I went a differnt route:


if [ $temp -ge 1 -a $temp -lt 100000 ] ; then
echo "The number, $temp is fine" ; break
else
echo "Error 21: Your input is less than 0 or greater than 100000"
echo "Or has characters other than numbers, change and resubmit"
echo ; continue
fi

This code kicks out all the things that aren't numbers. If the input is part alpha it just won't do the comparison and is kicked out to the else statement. I hate to do this in such a roundabout manner, but this is all I could get to work.

Ravioli
 
If $temp contains a non numeric character, you get an error message : 'bad number'.
If you want to avoid that, you can use the following test :
[tt]
if [[ $temp = +([0-9]) && $temp -lt 100000 ]]
[/tt]

Jean Pierre.
 
Thanks Jean Pierre. I get a chance to revise the program later this week. I would rather do this correctly and I know that +([0-9]) is the correct test. I will let you know how it goes.

Bradley
 
or simply

let $x 2> /dev/null || print not numeric greater than 0
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top