regex match in Bash if statement doesn't work

后端 未结 2 1133
面向向阳花
面向向阳花 2021-01-18 09:59

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

2条回答
  •  盖世英雄少女心
    2021-01-18 10:27

    There are two issues:

    First, replace:

    rh_reg="[rR]ed[:space:].*[Hh]at"
    

    With:

    rh_reg="[rR]ed[[:space:]]*[Hh]at"
    

    A character class like [:space:] only works when it is in square brackets. Also, it appears that you wanted to match zero or more spaces and that is [[:space:]]* not [[:space:]].*. The latter would match a space followed by zero or more of anything at all.

    Second, replace:

    [ "$getos" =~ "$rh_reg" ]
    

    With:

    [[ "$getos" =~ $rh_reg ]]
    

    Regex matches requires bash's extended test: [[...]]. The POSIX standard test, [...], does not have the feature. Also, in bash, regular expressions only work if they are unquoted.

    Examples:

    $ rh_reg='[rR]ed[[:space:]]*[Hh]at'
    $ getos="red Hat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos
    redhat
    $ getos="RedHat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos
    redhat
    

提交回复
热议问题