On Tue, 2003-02-11 at 16:07, Gordon wrote:
> I've searched all over for an answer to this and haven't found one yet!
> 
> Is there a way in a bash script to test if a variable contains an 
> integer? I want to create a script that uses some simple arithmetic but 
> bash bombs out if you try to do a comparison or arithmetic with a 
> non-numeric value. Basically, something like:

# note that weird things will happen if z is a multi-line variable

if echo "$z" | grep "^[0-9][0-9]*$" >/dev/null ; then
        echo z is a non-negative integer
else
        echo bad input ; exit 1
fi

or

if echo "$z" | grep "^[1-9][0-9]*$" >/dev/null ; then
        echo z is an integer greater than zero, no leading zeroes
else
        echo bad input ; exit 1
fi

you could probably do it in pure bash if necessary by using the builtin
arithmetic operators, but grep is best for portability.

hth,

-- 
[EMAIL PROTECTED]

[ do NOT use the following e-mail address: [EMAIL PROTECTED] ]



-- 
redhat-list mailing list
unsubscribe mailto:[EMAIL PROTECTED]?subject=unsubscribe
https://listman.redhat.com/mailman/listinfo/redhat-list

Reply via email to