JCats
JCats

Reputation: 141

bash IF not matching variable that contains regex numbers

DPHPV = /usr/local/nginx/conf/php81-remi.conf;

I am unable to figure out how to match a string that contains any 2 digits:

if [[ "$DPHPV" =~ *"php[:digit:][:digit:]-remi.conf"* ]]

Upvotes: 0

Views: 52

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You are not using the right regex here as * is a quantifier in regex, not a placeholder for any text.

Actually, you do not need a regex, you may use a mere glob pattern like

if [[ "$DPHPV" == *php[[:digit:]][[:digit:]]-remi.conf ]]

Note

  • == - enables glob matching
  • *php[[:digit:]][[:digit:]]-remi.conf - matches any text with *, then matches php, then two digits (note that the POSIX character classes must be used inside bracket expressions), and then -rem.conf at the end of string. See the online demo:
#!/bin/bash
DPHPV='/usr/local/nginx/conf/php81-remi.conf'
if [[ "$DPHPV" == *php[[:digit:]][[:digit:]]-remi.conf ]]; then
    echo yes;
else
    echo no;
fi

Output: yes.

Upvotes: 1

Related Questions