2

I am writing in bash, this script is supposed to output 'success', but it did not. Is the regex for numbers wrong?

var=5
if [[ "$var" =~ ^[:digit:]$ ]]; then 
    echo success
fi

Thnx!

Cyrus
  • 77,979
  • 13
  • 71
  • 125

2 Answers2

2

You will need to put [:digit:] inside a character class:

var=5
if [[ "$var" =~ ^[[:digit:]]$ ]]; then 
    echo success
fi

Also note that if you want to match multi digit numbers (> 9) you will need to use the plus metacharacter (+):

if [[ "$var" =~ ^[[:digit:]]+$ ]]; then 
    echo success
fi
Andreas Louv
  • 44,338
  • 13
  • 91
  • 116
  • 2
    In terms of naming, I think that `[:digit:]` is a character class but it needs to go inside a bracket expression `[]`. http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html#tag_09_03_05 – Tom Fenech May 16 '16 at 11:18
  • @TomFenech Thanks for clarifying. – Andreas Louv May 16 '16 at 11:19
0

You need to put the character class [:digit:] inside bracket expression []:

[[ "$var" =~ ^[[:digit:]]$ ]]

In ASCII locale, this is necessarily equivalent to:

[[ "$var" =~ ^[0-9]$ ]]
heemayl
  • 35,775
  • 6
  • 62
  • 69