-1

I have a program that takes arguments. I want to enforce that the arguments are integers. This is how I've been doing it.

allowed='^[0-9]+$'
if [[ $1 =~ $allowed ]]; then
    echo "number"
else
    echo "not a number"
fi

The problem with this is that it doesn't allow negative numbers because the dash at the beginning isn't a digit. How would I re-do the regex expression so that it allows negative numbers?

Herald
  • 1
  • a `-` followed by `?` (0 or 1 instances): `'^-?[0-9]+$'` – jordanm May 12 '22 at 00:15
  • Do you need to do it with regex? Another potential approach that works with POSIX shells is `if [ "$scale" -eq "$scale" ]` (per https://unix.stackexchange.com/a/151655) – jared_mamrot May 12 '22 at 02:51
  • @Nick he is asking for bash or shell, not python. – Nic3500 May 12 '22 at 03:18
  • @Nic3500 the regex is the same in that and the question you posted, for the most part (and certainly for something as simple as this) regex are language independent. – Nick May 12 '22 at 05:25

0 Answers0