0

I want to exclude everything which is not a number coming from my variable:

Example:

good variable: 4564 or 332 or 1

bad variable: er0rr or E131 or KE1

I'm not sure how to make if statement to recognize that the output is a number.

Kalin Borisov
  • 1,091
  • 1
  • 12
  • 23

1 Answers1

1

In BASH you can use this regex condition to check if variable n contains only digits:

[[ "$n" =~ ^[[:digit:]]+$ ]]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Or this extended glob pattern: `[[ $n = +([[:digit:]]) ]]`. Note that this doesn't guarantee that you'll be able to use this number in Bash's arithmetic context. For example, `n=09` passes this test, yet will raise an _09: value too great for base (error token is "09")_ error when used in arithmetic context. To fix this, you'll use, after this test, the following: `n=$((10#$n))`. – gniourf_gniourf Feb 13 '15 at 19:27