1
# Checking if we dealing with 1050 or 1050 Ti
function gpu_check() {
  test="GPU 0: GeForce GTX 1050 (UUID: GPU-97acce0b-4304-01e9-ef9d-bc3230cae912)"
  echo "testing $test"
  if [[ $test =~ "\sGTX\s1050\s" ]]; then
    echo "foud 1050"
  else
    echo "no 1050's here"
  fi
}

i'm trying to use regex but all possible variants i can imagine, like double \, adding * and .*, using "$test" and many more, giving me not what i'm expecting.

testing GPU 0: GeForce GTX 1050 (UUID: GPU-97acce0b-4304-01e9-ef9d-bc3230cae912)

no 1050's here

How do i make it work?

4
  • 1
    \s is a PCRE-ism. It's not available in BRE or ERE regex syntaxes. Commented Jul 23, 2017 at 18:55
  • What should i use insted? Commented Jul 23, 2017 at 18:56
  • 3
    @medik, wrong -- bash does have regex syntax. And please, please don't ever advise folks to use the ABS as a reference -- it's the W3Schools of shell scripting, full of bad-practice examples and outdated content. Commented Jul 23, 2017 at 18:58
  • @CharlesDuffy thanks, I didn't know that. Commented Jul 24, 2017 at 9:51

1 Answer 1

3
re='[[:space:]]GTX[[:space:]]1050[[:space:]]'
[[ $test =~ $re ]]

...will do the trick.

  • \s is PCRE syntax. =~ only guarantees POSIX ERE syntax, so PCRE extensions aren't available. [[:space:]] is the POSIX-compliant equivalent.
  • You can't quote the regex without making it literal. That is to say -- it must be =~ $re and not =~ "$re" if you want the value in re to be treated as a regular expression rather than an exact string to search for.

Quoting from the documentation on the bash-hackers wiki:

Using the operator =~, the left hand side operand is matched against the extended regular expression (ERE) on the right hand side.

This is consistent with matching against patterns: Every quoted part of the regular expression is taken literally, even if it contains regular expression special characters.

Best practice is to put the regular expression to match against into a variable. This is to avoid shell parsing errors on otherwise valid regular expressions.

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

1 Comment

Edit the typo please and i'll accept your answer. re=' bla "

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.