Why does the regex in bash works only if it is a variable and not directly?

6,551

Don't use the single quotes inside [[:

if [[ "$SOME_VAR" =~ ^test\/version[0-9]+([.][0-9]+)+$ ]]; then
    echo "Match!"
fi

From the GNU bash manual: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#Conditional-Constructs

Note in particular:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string.

The manual seems to suggest using the variable is preferred:

Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. It is sometimes difficult to specify a regular expression literally without using quotes, or to keep track of the quoting used by regular expressions while paying attention to the shell’s quote removal. Using a shell variable to store the pattern decreases these problems.

See also How does storing the regular expression in a shell variable avoid problems with quoting characters that are special to the shell?

Share:
6,551

Related videos on Youtube

Jim
Author by

Jim

Updated on September 18, 2022

Comments

  • Jim
    Jim over 1 year

    So why does the following works i.e. prints out the match:

    THE_REGEX='^test\/version[0-9]+([.][0-9]+)+$'
    if [[ "$SOME_VAR" =~ $THE_REGEX ]]; then
        echo "Match!"
    fi
    

    But the following does NOT:

    if [[ "$SOME_VAR" =~ '^test\/version[0-9]+([.][0-9]+)+$' ]]; then
        echo "Match!"
    fi  
    

    What is the difference? It is the same regex