Quote the right side of `==` for a literal match

Quoting the RHS of `[[ $x == $pattern ]]` disables glob matching. SC2053 flags cases where the pattern was probably meant to stay unquoted.

Problem

Inside `[[ ]]`, the right-hand side of `==`, `!=`, and `=` is treated as a glob pattern when left unquoted, so `[[ $file == *.txt ]]` performs pattern matching. Quoting that right-hand side (`[[ $file == "*.txt" ]]`) turns it into a literal string comparison, so `*.txt` no longer matches anything except the exact four characters `*.txt`. This becomes a bug when a variable holding a glob pattern is quoted "for safety" out of habit, silently turning an intended wildcard match into an always-false literal comparison.

Bad

pattern="*.txt"
if [[ "$file" == "$pattern" ]]; then   # literal compare, almost never matches
  echo "text file"
fi

Good

pattern="*.txt"
if [[ "$file" == $pattern ]]; then     # $pattern used as a glob
  echo "text file"
fi

Explanation

Quote the left-hand operand (`"$file"`) as always, but leave the right-hand pattern unquoted when it should be interpreted as a glob. If you actually want a literal string comparison, keep both sides quoted and drop any wildcard characters from the pattern, or use `[[ $file == "literal string" ]]` deliberately.

Related

SC2049

SC2076

SC2254

When It Matters

Inside [[ ]] the right side of == is a glob pattern, not a literal. Comparing against an unquoted variable means the variable’s contents are interpreted as a pattern, so a value containing *, ?, or [ matches things it should not. A permission check comparing a user-supplied role against a stored one can be satisfied by passing a single asterisk. That makes this an authentication-bypass shape, not just a correctness nit.

Second Example

Note

The rule of thumb: quote the right side unless you are deliberately writing a pattern, and write patterns as literals rather than storing them in variables.

Exceptions

When the variable really does hold a pattern supplied by your own configuration, the unquoted form is correct. Name the variable so this is obvious — pattern, glob, or match — and add a disable comment at the comparison.

Faq

Q

Does the same apply to = and != ?

A

Yes. Inside [[ ]] all of =, ==, and != perform pattern matching on an unquoted right side.

Q

What about single brackets?

A

[ ] does plain string comparison with no pattern matching, but it does word-split unquoted operands, so quoting is still required.

Q

How do I match a pattern held in a variable on purpose?

A

Leave it unquoted and comment the intent, or use =~ with a regex in a variable, which is the more conventional way to express dynamic matching.