Operating System - HP-UX
1831339 Members
3435 Online
110024 Solutions
New Discussion

In shell script ,how to check if type of a shell variable is integer ?

 
SOLVED
Go to solution
smilie
Occasional Advisor

In shell script ,how to check if type of a shell variable is integer ?

for exmaple,
var1=15
var2=abc

Thanks,
7 REPLIES 7
James R. Ferguson
Acclaimed Contributor

Re: In shell script ,how to check if type of a shell variable is integer ?

Hi:

The first usage of a variable determines its usage. *However* if you want to declare a variable as an integer, do:

# typeset -i N

This declares N as an integer, making arithmetic much faster.

Regards!

...JRF...
Craig Rants
Honored Contributor

Re: In shell script ,how to check if type of a shell variable is integer ?

I think what you are asking is a test to see if the the variable is an interger or a alpha character.

I think that ususally the person writing the script knows what form their data will be in and thus they will apply the interger or string comparision format to their test, i.e.
a = a or 1 -eq 1, I know of no check directly, if you are concerned then you could run a = and -eq test to see which works and determine it that way. Obviously not the most efficent way to code, but..


GL,
C
"In theory, there is no difference between theory and practice. But, in practice, there is. " Jan L.A. van de Snepscheut
A. Clay Stephenson
Acclaimed Contributor

Re: In shell script ,how to check if type of a shell variable is integer ?

Hi:

Here is a simple shell function that can be included to test to see if a variable is a valid integer. e.g. -1, 1234, 563 return 0 (good) but
12-34, 12.34, abc return 1 (bad).

Use it in your script like this:

var1=123
is_integer ${var1}
INTSTAT=$?
if [ ${INTSTAT} -eq 0 ]
then
echo "Good"
else
echo "Bad"
fi

Regards, Clay
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: In shell script ,how to check if type of a shell variable is integer ?

Ooops, I missed the attachment:



Clay

If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: In shell script ,how to check if type of a shell variable is integer ?

Hi (again):

One way to test a variable is this:

if [ `expr $VAR : '[0-9]*'` -eq `expr $VAR : '.*'` ]
then
echo "$VAR is an integer"
else
echo "$VAR is not an integer"
fi

Regards!

...JRF...
smilie
Occasional Advisor

Re: In shell script ,how to check if type of a shell variable is integer ?

James and Craig,

Thanks a lot. That's what I want. :-)
smilie
Occasional Advisor

Re: In shell script ,how to check if type of a shell variable is integer ?

and thanks Clay.