Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex stored in a shell variable doesn't work between double brackets

The below is a small part of a bigger script I'm working on, but the below is giving me a lot of pain which causes a part of the bigger script to not function properly. The intention is to check if the variable has a string value matching red hat or Red Hat. If it is, then change the variable name to redhat. But it doesn't quite match the regex I've used.

getos="red hat"
rh_reg="[rR]ed[:space:].*[Hh]at"
if [ "$getos" =~ "$rh_reg" ]; then
  getos="redhat"
fi
echo $getos

Any help will be greatly appreciated.

like image 440
dig_123 Avatar asked Feb 16 '18 05:02

dig_123


1 Answers

There are a multiple things to fix here

  • bash supports regex pattern matching within its [[ extended test operator and not within its POSIX standard [ test operator
  • Never quote our regex match string. bash 3.2 introduced a compatibility option compat31 (under New Features in Bash 1.l) which reverts bash regular expression quoting behavior back to 3.1 which supported quoting of the regex string.
  • Fix the regex to use [[:space:]] instead of just [:space:]

So just do

getos="red hat"
rh_reg="[rR]ed[[:space:]]*[Hh]at"
if [[ "$getos" =~ $rh_reg ]]; then 
    getos="redhat"
fi;

echo "$getos"

or enable the compat31 option from the extended shell option

shopt -s compat31
getos="red hat"
rh_reg="[rR]ed[[:space:]]*[Hh]at"
if [[ "$getos" =~ "$rh_reg" ]]; then 
    getos="redhat"
fi
echo "$getos"
shopt -u compat31

But instead of messing with those shell options just use the extended test operator [[ with an unquoted regex string variable.

like image 120
Inian Avatar answered Nov 14 '22 18:11

Inian