Mac
Mac

Reputation: 111

How to validate that a parameter is an integer number in UNIX?

I am writing a script where the second parameter must be an integer, but I don't know how to check if a parameter is an integer or not.

if test $2 =~ "^[0-9]+$"
 then
  echo "\nNumero  entero"
 else
  echo "\nError: El numero $2 no es un numero entero !!!\a"
 fi

Upvotes: 1

Views: 120

Answers (1)

aalazz
aalazz

Reputation: 1269

Almost. I'm assuming a bash shell:

#!/bin/bash
result=$(echo "$2" | grep '^[0-9][0-9]*$')
if [ -n "$result" ]
then
    echo 'Integer!'
else
    echo "Error: '$2' is not an integer"
fi

Upvotes: 1

Related Questions