How to validate if a parameter is a whole number in UNIX?

8

I have to make a script that receives two parameters, of which the second must be a whole number. I have no idea how to validate that.

 if test $2 =~ "^[0-9]+$"
 then
  echo "\nNumero positivo entero"
 else
  echo "\nError: El numero $2 no es un numero entero positivo!!!\a"
 fi
    
asked by Mac 15.03.2016 в 02:20
source

4 answers

3

You can use regular expressions to validate numbers, whether they are integers, negative integers or decimals, you could do something like this:

validate_number=^-?[0-9]+([.][0-9]+)?$;
echo "Please Enter your number ";
read number
if ![[ $number =~ $validate_number ]]; then
echo "number not valid"
fi

the regular expressions are:

[1.] ^ -? this expression verifies the beginning of the string and if it contains some character only one -

[2.] [0-9] verify that they are numbers from 0 to 9

[3.] the character + specifies the operator or

[4.] ([.] [0-9] +) $ confirms if the entered value was a decimal number and verifies the end of the string with $

The previous code receives a keyboard argument and verifies if the input was really a number, whether positive, negative or decimal

    
answered by 15.03.2016 / 05:50
source
0

Can be validated with a case :

case $2 in
(""|*[^0-9]*) printf "\nError: ¡¡¡ [$2] no es un número entero positivo !!!
case $2 in
(""|*[^0-9]*) printf "\nError: ¡¡¡ [$2] no es un número entero positivo !!!%pre%7\n";;
(*) printf "\nNúmero entero positivo\n";;
esac
7\n";; (*) printf "\nNúmero entero positivo\n";; esac
    
answered by 15.03.2016 в 04:20
0

You can perform a method that receives parameters, that takes the value of the second and validates whether it is Integer or not, for example:

esEnteroSegundoParametro() {

    echo "Valor parametro #1 is $1"
    echo "Valor parametro #2 is $2"

    #Revisa si el segundo parámetro es un entero.
    if echo "$2" | egrep -q '^\-?[0-9]+$'; then 
       echo "$2 es un entero."
    else 
       echo "$2 NO es un entero."
    fi
}

If we execute the method with the following values:

esEnteroSegundoParametro 14 12.2 

we get:

If we execute the method with the following values:

esEnteroSegundoParametro 14 12 

we get:

    
answered by 16.03.2016 в 00:06
0

What you can do is filter it by error control seeing that if it is a digit and if it is greater than 0 it is a whole number but, no, not.

echo -en $caracter | grep '[[:digit:]]' > /dev/null 2> /dev/null
if [ $? -eq 0 && $caracter -gl 0 ]
then
    echo "Es un digito entero"

# Si no, mostrem un missatge indicant que no és ni lletra ni nombre
else
    echo "No es un digito entero"
fi
    
answered by 29.04.2016 в 12:25