85

I want to check if a variable has a valid year using a regular expression. Reading the bash manual I understand I could use the operator =~

Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?

i="test"
if [ $i=~"200[78]" ]
then
  echo "OK"
else
  echo "not OK"
fi
2
  • possible duplicate of bash regex with quotes? Commented Apr 1, 2012 at 3:24
  • Note this was failing because of the lack of spaces around =~. Commented Jun 20, 2016 at 9:24

2 Answers 2

118

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

How do i handle the situation when the regex contains spaces if I cannot quote? If the regex is e.g. a +b it will report a syntax error...
@Alderath: Use a\ \+b to escape the space and the plus character.
8

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

1 Comment

paxdiablo's answer is right, adding spaces here does not help (you now also get "not OK" for 2008, the only string that gets matched is literally "200[78]").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.