Check if variable is a positive integer

Asked

Viewed 1,617 times

8

To check if a variable is a integer positive, I am using 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 be the best approach to dealing with this issue or we can simplify the process and avoid regular expressions?

5 answers

5

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

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

I found it pertinent to post because it’s not just another variation of regex, like several I’ve seen.

  • +1 Effectively an alternative, although in a slightly different model than the one posed in the question.

4


A way to do it without use regular expression, is to evaluate an expression with the command expr, that 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 if it is a positive integer, the operator is used gt (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 the use of regular expressions may not be a good idea, unless you need to do the same task on several systems where the syntax, the engine, is incompatible with each other.

In the article below it addresses this subject more deeply:

1

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

There’s that way too.

1

I believe that the @stderr method is the simplest because it uses directly the output status of the 'expr' command, as well as being portable. Simplifying a little more:

[ `expr "$var" + 0 2>&-` ] && [ $var -gt 0 ] && echo 'Número inteiro positivo'

'2>&-' deletes the error output, such as 2>/dev/null. In this case the test command does not need the if'.

0

I will use a different approach, I will use a script in Pyton within the Shell Script.

The goal is not to be better or faster, so much so that the other answers are arguably good, but to show a possibility of integration between Shell and its favorite programming language and solve the proposed problem according to the specified parameters.

The algorithm is simple:

Verifique o tipo do primeiro parâmetro de entrada...
     ...se for inteiro retorna Verdadeiro.
     ...se não for inteiro falso retorna Falso.

So the script went like this:

#!/bin/bash

t=$1


{  echo 'print(type(' $t ') is int)'; } | python -u

Browser other questions tagged

You are not signed in. Login or sign up in order to post.