Operating System - Linux
1821980 Members
3106 Online
109638 Solutions
New Discussion юеВ

checking if a variable is an integer or a string

 
SOLVED
Go to solution
itai weisman
Super Advisor

checking if a variable is an integer or a string

hello,
does anyone know how can I check whether a varible value contains an integer or a string?
on simple bourne shell script
Itai
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: checking if a variable is an integer or a string

We will leverage enhanced grep (-E) and use an anchored (at both ends) pattern; use the -q option because we only care about the status of the matched string :

echo "${MYVAR}" | grep -E -q -e '^-{0,1}[0-9]+$'
GSTAT=${?}
if [ ${GSTAT} -eq 0 ]
then
echo "${MYVAR} is an integer"
else
echo "${MYVAR} ain't an integer"
fi

You can drop the -{0,1} if only positive values pass the test.

If it ain't broke, I can fix that.
Robert-Jan Goossens_1
Honored Contributor

Re: checking if a variable is an integer or a string

Hi,

There are a lot of examples inside the ITRC, check below link.

http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=66578

search I used in google "site:forums1.itrc.hp.com integer string"

Best regards,
Robert-Jan
Bill Hassell
Honored Contributor

Re: checking if a variable is an integer or a string

In Unix, if you don't find at least 5 different ways to do the same thing, you aren't looking hard enough. Here's an interesting method: Use tr to remove digits and see if anything is left:

if [ "$(echo $MYVAR | tr -d '[:digit:]')" = "" ]
then
echo "All digits"
else
echo "$MYVAR has non-digits"
fi


Bill Hassell, sysadmin
Stephen Keane
Honored Contributor

Re: checking if a variable is an integer or a string

As Bill says ...


Say your variable is called $VAR.

typeset -i INT="$VAR" 2> /dev/null
if [ "$?" -eq 0 ]
then
echo "Is an integer"
else
echo "Is not an integer"
fi

itai weisman
Super Advisor

Re: checking if a variable is an integer or a string

thanks everyone,
you really helped my a lot