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 Effectively an alternative, although in a slightly different model than the one posed in the question.
– Zuul