84

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
Hamish Downer
  • 16,603
  • 16
  • 90
  • 84
idrosid
  • 7,983
  • 5
  • 44
  • 41

2 Answers2

117

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
Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    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 Aug 06 '13 at 13:04
  • 5
    @Alderath: Use `a\ \+b` to escape the space and the plus character. – blinry Aug 18 '13 at 09:27
8

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi
michiel
  • 97
  • 1
  • 1
  • 3
    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]"). – Marcel Stimberg Sep 26 '12 at 17:41