Reputation: 23
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!
Upvotes: 2
Views: 61
Reputation: 42007
You need to put the character class [:digit:]
inside bracket expression []
:
[[ "$var" =~ ^[[:digit:]]$ ]]
In ASCII locale, this is necessarily equivalent to:
[[ "$var" =~ ^[0-9]$ ]]
Upvotes: 0
Reputation: 47099
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
Upvotes: 2