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!

Numeric Check

Status
Not open for further replies.

vodkadrinker

Technical User
May 16, 2002
163
GB
Quick question on a numeric check in an if statement.

The user can input any number

if [ $numberinputbyuser = number ] ; then

do
whatever...
 
The '=' sign is string comparison. What you want is one of
Code:
if [ $numberinputbyuser -eq $testnumber ]
then
  do something
fi
or, if you're creating a menu, for example
Code:
case $numberinputbyuser in
  1) do option 1;;
  2) do option 2;;
  3) do option 3;;
  *  do unknown option;;
esac
but we're back to string equality. i.e. if the user inputs '01' it won't match option 1

On the internet no one knows you're a dog

Columb Healy
 
I guess I could do a case statement to check for a numeric I was just wondering if there was an easy if statement just to see if an input was numeric or not.

case $numberinputbyuser in
[1-9]" "[1-9]|[1-9]" "[1-9][0-9]|[1-9]" "[1-9][0-9][0-9]|[1-9][0-9]" "[1-9][0-9]|[1-9][0-9]" "[1-9][0-9][0-9]|[1-9][0-9][0-9]" "[1-9][0-9][0-9])
do whatever...
;;
*)
do whatever...
;;
esac
 
or something more for my original question.

case $numberinputbyuser in
[1-9]|[1-9][0-9]|[1-9][0-9][0-9])
do whatever...
;;
*)
do whatever...
;;
esac
 
In ksh you may use typeset -i to force a variable to be numeric.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Sorry, misunderstood your question
Something like
Code:
expr "$numberinputbyuser" : "[0-9]*$" > /dev/null && echo $numberinputbyuser is numeric

On the internet no one knows you're a dog

Columb Healy
 
How about something like:

if [[ "$numberinputbyuser" = ?([+-])+([0-9]) ]]
then
do whatever for numbers (optionally signed integers) input ....
fi

Tested in Korn Shell on Solaris.

I hope that helps.

Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top