if with regex in bash code

Far simpler just to check the release string directly

if grep -q 'release 7\.[56] ' /etc/redhat-release
then ...

The grep command matches by regular expression. The [56] atom matches 5 or 6, allowing the pattern to match on 7.5 or 7.6. Since . matches any character I've escaped it with a backslash so that it matches a literal dot. The trailing space ensures there are no other characters following the matched version string.


You can do this with bash's built-in string matching. Note that this uses glob (wildcard) patterns, not regular expressions.

if [[ $(cat /etc/redhat-release  | awk '{print $7}') == 7.[56] ]]

Or, of we eliminate the UUoC:

if [[ $(awk '{print $7}' /etc/redhat-release) == 7.[56] ]]

or...

if [[ $(cat /etc/redhat-release) == *" release 7."[56]" "* ]]

or even (thanks to @kojiro)...

if [[ $(< /etc/redhat-release) == *" release 7."[56]" "* ]]

(Note that wildcards at the beginning and end are needed to make it match the entire line. The quoted space after the number is to make sure it doesn't accidentally match "7.50".)

Or if you really want to use regular expressions, use =~ and switch to RE syntax:

if [[ $(< /etc/redhat-release) =~ " release 7."[56]" " ]]

(Note that the part in quotes will be matched literally, so . doesn't need to be escaped or bracketed (as long as you don't enable bash31 compatibility). And RE matches aren't anchored by default, so you don't need anything at the ends like in the last one.)


awk can do all the work of cat and [[...]] here:

if
  </etc/redhat-release awk -v ret=1 '
    $7 ~ /^7\.[56]$/ {ret=0}
    END {exit(ret)}'
then
  ...

Or just with standard sh syntax with simple wildcard pattern matching:

case $(cat /etc/redhat-release) in
  (*'release 7.'[56]' '*) ...;;
  (*) ...;;
esac