Todd A. Jacobs wrote:
On Tue, 11 Feb 2003, Gordon wrote:


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

Nope. You'll have to do something more arcane:

    function IsInt {
	if egrep -q '[[:digit:]]+' <(echo $1)
	then
	    return 0
	else
	    return 1
	fi
    }

Another possibility is to exploit the builtin command typeset, like:

typeset -i x # Now x is an integer variable
echo $x # Returns an empty line
x=123456
echo $x # Returns 123456
x="abcdef"
echo $x # Returns 0

Thus:

typeset -i x
a="abcdef"
x=$a
if [[ "$x" = "$a" ]]
...

The comparison will test true, if a is an integer and false if not. (I know we are supposed to use '==' instead of '=' in tests, but it is not always recognized, especially by ksh on HPUX.)

/jan



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

Reply via email to