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
  • 69,405
  • 13
  • 65
  • 117

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
andlrc
  • 41,466
  • 13
  • 82
  • 108
  • 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. – andlrc 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
  • 32,535
  • 3
  • 52
  • 57