Thursday, August 29, 2013

Solution : Check Variable in Linux Bash is Float or Interger

Hi,

Here solution for checking a variable in Linux Bash is Float or Integer by using grep.

---- file :  test.sh

function check_int(){
echo $1 | grep "^[0-9]*$" > /dev/null
if [ $? -ne 0 ]; then
echo $2 : $1 is not a number;
        else
                echo $2 : $1 is a number
fi
}

function check_float() {
echo $1 | grep "^[0-9]*\.[0-9]*$" > /dev/null
if [ $? -ne 0 ]; then
check_int $1 $2
        else
                echo $2 : $1 is a float number
fi
}



check_int 12 my_number
check_float  12.2 my_number

check_int 12a my_number
check_float  12a2 my_number

--------------------

yadavmahi@localhost:~/MahiYadav/scripts> bash test.sh
my_number : 12 is a number
my_number : 12.2 is a float number
my_number : 12a is not a number
my_number : 12a2 is not a number


0 comments:

Post a Comment