1

I'm having problem with bash regex match. I have regex like this:

re="fatal: file not found: .+/tmp_dir_1234/([^\ ]*) \(No such file or directory\)"
test="fatal: file not found: /some/path/irrelevant/something/tmp_dir_1234/somefile.txt (No such file or directory)"
if [[ "$test" =~ "$re" ]]; then
    echo "match!"
fi

For me everything here looks good for now but for some reason while debugging bash script I can see that it doesn't match string here:

+ [[ fatal: file not found: /some/path/irrelevant/something/tmp_dir_1234/somefile.txt (No such file or directory) =~ fatal: file not found: \.\+/tmp_dir_1234/\(\[\^\\ ]\*\) \\\(No such file or directory\\\) ]]

For some reason regex pattern is escaped.

J33nn
  • 3,034
  • 5
  • 30
  • 46

1 Answers1

8

Remove the double quotes from the regular expression in the match:

if [[ "$test" =~ $re ]]; then
    echo "match!"
fi

In double square brackets, there is no need to quote variables, as they are parsed in a special way. See man bash for details:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Your answer is correct. To make this answer awesome, I would also suggest changing `"$test"` to `$test` and adding some notes about [word splitting](https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html) in [conditional expressions](https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#index-_005b_005b). – Go Dan Mar 17 '14 at 13:38