2

Alright folks. I am writing a bash script and would like compare a string against a regular expression containing a # using the =~ operator.

Here is what I have so far:

if [[ ${line} =~ \s*\# ]]; then
     #do things
fi

As you can see, I am attempting to escape the # with a \, which is supposed to be possible according to this article. This is really confounding to me, however. My syntax highlighter is still highlighting the text following the # as if it were a comment.

Is my syntax highlighter incorrect? Will the escape of the # interfere with the parsing of the regex? Is there some way I can use quotes to avoid this issue?

4
  • Expecting your editor's syntax highlighter to get this right is, frankly, asking too much of it. @anubhava's answer is a good one, but it's a fix for your editor's highlighter (and for consistent behavior with really old versions of bash that are never seen in practice anymore), not something with impact on shell behavior on modern implementations. Commented Jul 2, 2015 at 20:44
  • Incidentally, # is never a shell comment character when it exists partway through a word, so your editor is really, really off here. Commented Jul 2, 2015 at 20:46
  • default red hat vimrc is what I am using :P Commented Jul 2, 2015 at 20:49
  • Hmm. If I weren't busy right now, I'd be tempted to go submit a patch... Commented Jul 2, 2015 at 20:50

1 Answer 1

5

You can do:

re='\s*#'

if [[ $line =~ $re ]]; then
     #do things
fi
Sign up to request clarification or add additional context in comments.

4 Comments

great, thanks. I wasn't sure if quotes would work properly with the =~ operator... I still don't fully understand their use in control flow statements
Quoted text doesn't work on RHS of =~ operator but variables can be used as I showed above.
A quoted string simply escapes every character ("foo" and \f\o\o produce identical strings, for instance). It's the result after quote removal that is assigned to the variable, so there's no way to tell if the assignment was re="foo" or re=\f\o\o or re="of"o or any other possibility: the end result is a variable containing a string of 3 characters.
(Also, you can quote some text on the RHS, just not any characters that are intended as metacharacters. [[ foo =~ "fo*" ]] won't succeed, but [[ foo =~ "fo"* ]] would match as expected.)

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.