1

I'm trying to use regext to detect if a string starts with a specific pattern or not but it does not work with me:

   #!/bin/bash
   line="{{ - hello dear - }}"
   if [[ "${line}" =~ ^\{\{\s*-\s*hello\s*.*\}\} ]]; then
        echo "got it "
   fi

In this example, I expect the if condition to detect that the line variable has a string that starts with "{{ - hello" and ends with "}}" However, it does not do so as the echo message is not printed!

3
  • bash version is: GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu) Commented Jan 6, 2022 at 18:43
  • 3
    I don't think bash regexp supports \s escape sequence. Commented Jan 6, 2022 at 18:46
  • 2
    Please add your desired output (no description, no images, no links) for that sample input to your question (no comment). Commented Jan 6, 2022 at 18:52

2 Answers 2

2

You can store the regex in a variable to make it work. It was a workaround in 3.2. Not sure why it's needed again in newer versions.

#!/bin/bash

line="{{ - hello dear - }}"
regex='^\{\{\s*-\s*hello\s*.*\}\}'

if [[ "${line}" =~ $regex ]]; then
     echo "got it "
fi

Also consider using extended pattern matching with == instead. I believe it has a weaker "engine" but it's more readable sometimes.

shopt -s extglob
...
[[ $line == "{{ - hello dear - }}"* ]] && echo "Got it."

(Actually that's not even an extended pattern yet.)

Sign up to request clarification or add additional context in comments.

3 Comments

Warning! using \s only works on Linux (tested on macOS, FreeBSD and Solaris)
@Fravadona What version of Bash do you use? I just tested it again with 3.2, 3.2.46, 4.0, 4.4 and latest and it works.
I see you changed your comment. Yes that might be the case for non-Linux. Regex is most likely parsed by a different engine in others.
1

There is no real need to use regex here. You can just use glob matching in bash like this:

line="{{ - hello dear - }}"

[[ $line == '{{ - hello'*'}}' ]] && echo "got it "

got it

Comments

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.