Operating System - HP-UX
1753505 Members
4542 Online
108794 Solutions
New Discussion юеВ

Minor shell script question

 
SOLVED
Go to solution
Achilles_2
Regular Advisor

Minor shell script question

Hello there,

I don't know how to write the statement in order to distinguish the input is integer. it seems as below

if [ $1 is an integer ]; then
echo "it is an intger"
else
echo "it is a string"
fi

Thanks
6 REPLIES 6
john korterman
Honored Contributor
Solution

Re: Minor shell script question

Hi Achilles,

I think you have to be a little creative to achieve that. This example just deletes all numbers in $1 and if anything still remains, $1 was not an integer:


#!/usr/bin/sh
REST=$(echo "$1"|tr -d [0-9])
if [ "$REST" = "" ]; then
echo "it is an intger"
else
echo "it is a string"
fi

regards,
John K.
it would be nice if you always got a second chance
Peter Godron
Honored Contributor

Re: Minor shell script question

James R. Ferguson
Acclaimed Contributor

Re: Minor shell script question

Hi:

This handles the determination of unsigned integers:

# N=123
# [ `expr "${N}" : '[0-9]*'` -eq `expr "${N}" : '.*'` ] && echo "Integer" || echo "non-integer"

If the value of 'N' consists only of the digits 0-9 for its whole length, then 'N' is an integer.

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Minor shell script question

Here's one approach:

sub is_signed_int
{
typeset -i GSTAT=255
if [[ ${#} -eq 1 ]]
then
echo "${1}" | grep -E -q '^[+-]{0,1}[0-9]+$'
GSTAT=${?}
else
echo "Function is_signed_int expects exactly 1 arg" >&2
fi
return ${GSTAT}
} # is_signed_int


sub is_int
{
typeset -i GSTAT=255
if [[ ${#} -eq 1 ]]
then
echo "${1}" | grep -E -q '^[0-9]+$'
GSTAT=${?}
else
echo "Function is_int expects exactly 1 arg" >&2
fi
return ${GSTAT}
} # is_int

typeset -i STAT=0

while [[ ${#} -ge 1 ]]
do
echo "Value ${1} \c"
is_signed_int "${1}"
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then
echo "is a signed int \c"
fi
is_int "${1}"
if [[ ${STAT} -eq 0 ]]
then
echo "is an int\c"
fi
echo
shift
done


The -q option of egrep returns an exit code of 0 if the pattern matches the regular expression and non-zero otherwise.
If it ain't broke, I can fix that.
Achilles_2
Regular Advisor

Re: Minor shell script question

Thanks you for ALL help. I have achieved what I need.
Achilles_2
Regular Advisor

Re: Minor shell script question

I closed this subject now