How do I use regular expressions in bash scripts?

RegexBashConditional

Regex Problem Overview


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

Regex Solutions


Solution 1 - Regex

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

Solution 2 - Regex

You need spaces around the operator =~

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionidrosidView Question on Stackoverflow
Solution 1 - RegexpaxdiabloView Answer on Stackoverflow
Solution 2 - RegexmichielView Answer on Stackoverflow