koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts
https://www.shellcheck.net
GNU General Public License v3.0
36.11k stars 1.77k forks source link

[SC2252] False positive with POSIX-compliant prefix string match #1755

Open rassie opened 4 years ago

rassie commented 4 years ago

For bugs

Here's a snippet or screenshot that shows the problem:


#!/bin/sh
if [ "$A" != "${A#substring1}" ] ||
   [ "$A" != "${A#substring2}" ] ||
   [ "$A" != "${A#substring3}" ]; then
    echo "substring matched"
    exit 0
fi

Here's what shellcheck currently says:

SC2252: You probably wanted && here, otherwise it's always true.

Here's what I wanted or expected to see:

This expression is perfectly valid and not always true. The idea is to check for string prefix match in $A, which has to be either substring1, substring2 or substring3 to execute the code in the then block. Since I can't use bash pattern globs, a technique is used which compares the original string with the same string without a prefix to get the idea whether the original string actually starts with that prefix. I would expect shellcheck not to warn about this expression.

matthewpersico commented 4 years ago

Then don’t you want = instead of !=?

rassie commented 4 years ago

No, since != means "match" in this case. If I want to match for bar and compare foobar with foo (foobar without bar) and there aren't equal, then it's a match. If I instead compare fuzzbuzz with fuzzbuzz (fuzzbuzz without bar), those are equal, which means it's not a match. Complicated, I know :)