0

I am using regular expressions and wildcards in if statements.

Examples:

  [[ "$exitfn" =~ ^[yY]*$ ]] && return
  [[ "$exitfn" == "[yY]*" ]] && return
  [[ "$exitfn" == "*$fs*" ]] && return
  [[ "$exitfn" == *$fs* ]] && return

But really wonder about any difficulties introduced if I quote *$fs*" or do not quote *$fs*.

Also wondering about using =~ against ==.

Pietru
  • 389
  • 1
  • 17
  • Did you test those to see what differences there are? Also, see e.g. http://mywiki.wooledge.org/BashGuide/TestsAndConditionals and https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#Conditional-Constructs and https://unix.stackexchange.com/q/306111/170373 – ilkkachu Jul 25 '21 at 19:42
  • also: https://unix.stackexchange.com/q/32119/170373 – ilkkachu Jul 25 '21 at 19:44
  • Is the string in $fs a glob pattern (use unquoted with ==), a regular expression (use unquoted with =~), or a literal string (use quoted with either == or =~ depending on the rest of the pattern)? – Kusalananda Jul 25 '21 at 19:51
  • $fs is not a glob pattern. – Pietru Jul 25 '21 at 20:48

1 Answers1

5

The right-hand side of == or != within [[...]] is a glob pattern -- == and != are not string equality operators, they are pattern matching operators.

In a regex or a glob pattern, any quoted part is considered literal text.

[[ "$exitfn" =~ ^[yY]*$ ]] && return
  • this works as expected
[[ "$exitfn" == "[yY]*" ]] && return
  • this only returns if the variable is the literal text [yY]*
[[ "$exitfn" == "*$fs*" ]] && return
  • this only returns if the variable contains an asterisk followed by the contents of $fs followed by an asterisk
[[ "$exitfn" == *$fs* ]] && return
  • this should work as expected unless the expansion of $fs can be matched as a glob expression.
    • for example: if fs='???' then return will be executed if $exitfn contains at least 3 characters.

tl;dr -- you want

  [[ "$exitfn" == *"$fs"* ]] && return
glenn jackman
  • 85,964