LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Help Me! (http://www.linuxquestions.org/questions/linux-general-1/help-me-463999/)

FrankCappas 07-14-2006 09:46 AM

Help Me!
 
Using Linux - bash
I am working on a shell scrip where I ask to input a "whole number". How can make a check to see if the number they input is a whole number? If is not a whole number I will write an error message and send back to "Input a Whole Number".

Please help! E-mail me back at Frank.Cappas@CIGNA.Com is you can.


Frank

Matir 07-14-2006 10:02 AM

For future reference, please select a topic that better describes your problem, like "BASH Script - Input Whole Number" or something similar.

As far as I know, there's no easy way to confirm that the value entered by a user is an integer. I would think that the following would work, though:
Code:

if [ $(($VAR + 0)) != $VAR ]
    then echo Not an integer.
else
    echo Integer found.
fi


AarnoK 07-15-2006 08:42 AM

Just trying to add zero does not really work, as it will produce
syntax error if the input was not an integer.
But then we can use this fact in the following way:

Code:

#!/bin/bash

echo -n "Enter a number: "
read val
haveInteger=0
(test $(($val+0)) == $val)2>/dev/null && haveInteger=1
if [ $haveInteger == 1 ]
  then echo Got an integer.
  else echo Not an integer.
fi

Integers will pass the test command, but anything else fails
and $haveInteger remains zero.

- Aarno

Matir 07-15-2006 09:04 AM

I got no syntax error in testing my code, unless $VAR is not set, or is an empty string. Can you demonstrate the circumstances in which an error occurs?
Code:

if [ -z $VAR ]
    then echo Null string\!
    return 1
fi
if [ $(($VAR + 0)) != $VAR ]
    then echo Not an integer.
else
    echo Integer found.
fi


AarnoK 07-15-2006 09:17 AM

The first approach works fine for separating words from integers,
but for decimal numbers I got, for example

Enter a number: 3.14
./ww.bash: line 6: 3.14 + 0: syntax error in expression (error token is ".14 + 0")

Cheers, Aarno

Matir 07-15-2006 07:51 PM

Ah, very true. I (sadly) did not thoroughly test my code. I had tried begins-with-. decimals (i.e, .12), strings, integers, and nulls, but no >1 decimals.

anupamsr 08-01-2006 08:10 PM

May be this can help?
Code:

#!/bin/bash

read VAR
if [ `echo "$VAR/1" | bc -l | tail -c21` != 00000000000000000000 ]; then
        echo Not a whole number
else
        echo Whole number
fi


ckin2001 08-02-2006 12:10 AM

http://sources.gentoo.org/viewcvs.py...ash.in?rev=183

They have a function to make sure the user inputs a positive whole number. A far easier way to do this is to assume that anything without a decimal is a whole number, and anything with one is not.

Hint : AWK


All times are GMT -5. The time now is 11:24 AM.