Check if variable is a positive integer

6

To check if a variable is a positive integer , I'm resorting to a regular expression:

#!/bin/bash

id="$1"
regNumTest='^[0-9]+$'

if ! [[ "$id" =~ $regNumTest ]]; then
    echo "Parâmetro #1 deverá ser um inteiro!"
    exit 0
fi

Will it be the best approach to address this issue or can we simplify the process and avoid regular expressions?

    
asked by anonymous 25.03.2015 / 16:08

3 answers

3

One way to do this without using the regular expression is to evaluate an expression with the expr , which will return the exit code 2 if the expression is invalid (for example, letters ), 3 if an error occurs, or 0 if the operation is successful.

To check for a positive integer, the gt operator is used ( is greater than).

#!/bin/bash

id=$1;

if expr "$id" + 0  > /dev/null 2>&1 && [ "$id" -gt 0 ]; then
    echo "$id é um inteiro positivo"
else
    echo "$id não é inteiro positivo"
fi
Avoiding regular expressions may not be a good idea, unless you have to do the same task on many systems where the syntax, the engine, is incompatible with one another.

The article below addresses this issue more deeply:

25.03.2015 / 17:19
4

This is a alternative that I saw in SOzão , which I liked for being more "portable":

case $string in
    ''|*[!0-9]*) echo bad ;;
    *) echo good ;;
esac

I found it appropriate to post because it was not just another variation of regex , like several I've seen.

    
25.03.2015 / 16:39
0
if [[ $var = ?(+|-)+([0-9]) ]] ; then 
echo "$var é um numero"
else
echo "$var não é um numero"
fi

It has that way too.

    
12.02.2017 / 02:24