Colin
Colin

Reputation: 113

Bash shell if statement matching regex with curly braces {}

I've been writing a little bash script to aid less experienced Linux users with some commands. One thing seems to be escaping me and that's using curly braces when doing pattern matching for an if statement.

regex="[A-Za-z0-9]/{5/}"
if [[ $2 =~ $regex ]]
then
  num=$2
else
  echo "Invalid entry"
  exit 1
fi

This should capture anything A-Z, a-z or 0-9 that is exactly 5 characters, should it not?

I've tried many times, many variations, many quotes, with and without escaping... Nothing seems to be working:

+ regex='[A-Fa-f0-9]/{5/}'
+ [[ abcd1 =~ [A-Za-z0-9]/{5/} ]]
+ echo 'Invalid entry'

Any ideas what I'm missing?

GNU bash, version 3.2.39(1)-release

Upvotes: 2

Views: 15689

Answers (3)

Nico Rodsevich
Nico Rodsevich

Reputation: 2575

Maybe the problem is here:

regex="[A-Za-z0-9]/{5/}"

Should be:

regex="[A-Za-z0-9]\{5\}"

(watch backslashes)

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247012

Hmm, works for me in bash version "GNU bash, version 4.1.10(4)-release"

$ regexp="[[:alnum:]]{5}"
$ set -- "" abcde
$ [[ "$2" =~ $regexp ]] && echo y || echo n
y
$ set -- "" foo
$ [[ "$2" =~ $regexp ]] && echo y || echo n
n

Note that the right-hand side must not be quoted:

$ set -- "" abcde
$ [[ "$2" =~ "$regexp" ]] && echo y || echo n
n

You don't actually need a regular expression for this:

$ glob="[[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]]"
$ set -- "" abcde
$ [[ "$2" == $glob ]] && echo y || echo n
y
$ set -- "" foo
$ [[ "$2" == $glob ]] && echo y || echo n
n

Upvotes: 1

murgatroid99
murgatroid99

Reputation: 20297

You should try

regex="[A-Za-z0-9]{5}"

Edit: Another change you could try is

if [[ "$2" =~ $regex ]]

Edit2: If you just want to determine if $2 is 5 characters long, you could try something like

if [ ${#2} = 5]

Upvotes: 1

Related Questions