1

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
Adam B
  • 3,775
  • 3
  • 32
  • 42
Mac
  • 111
  • 7
  • 14

1 Answers1

1

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
aalazz
  • 1,239
  • 11
  • 15
  • D: It throws me this: grep: illegal option -- E Usage: grep -hblcnsviw pattern file . . . – Mac Mar 15 '16 at 02:04
  • 1
    and this? grep '^[0-9][0-9]*$' – aalazz Mar 15 '16 at 02:07
  • Now it works! Thanks a lot man... Hey but could you tell me what topic should I search to learn more about? – Mac Mar 15 '16 at 02:09
  • 1
    You should try to learn about the shell you're using. I assumed bash because it's the most common. For example: http://stackoverflow.com/questions/4651437/how-to-set-a-variable-equal-to-the-output-from-a-command-in-bash and, of course, the command "man grep" or any text about regular expressions – aalazz Mar 15 '16 at 02:15