-like is used to look for string matches and allows you to use wildcard characters like
* (one or more characters) and
? (exactly one character). For instance, to look if the string
test matches the string
ThisTest, all I have to type is
"ThisTest" -like "*test*", which is true. Likewise, both
"ThisTest" -like "*test" and
"ThisTest" -like "????test" return
I can’t hide the fact I’m pretty intrigued by the fact there’s no direct equivalent in Bash. The closest thing to
-like I can think of on a Unix’ is
grep – which is a command and not an operator. Speaking of which,
grep-lovers should be aware that
-like gives us a true value only if a full match happens. Therefore,
"ThisTest" -like "test" evaluates to false.
The syntax for all comparison operators is the same:
a -operator b. To be honest, for me this is logical for almost all operators (think
-ge, etc.), but I still find it cumbersome to read when I use
-like (or even
StringToSearch -like Pattern just doesn’t feel right.
The other operator,
-contains, returns true if a collection contains the element on the right side of the operator. Easier shown than explained:
"This","Test" -contains "test"
is True. This works in a similar fashion to Python’s
in operator. Again, though, discretion is advised. If we type
"ThisTest" -contains "test" we’ll end up seeing
False in the console. This is simply because, unlike in Python, strings are not collections.
A final note about the return value. We might expect all operators to return a Boolean value, but this is not always the case. Actually, quite the contrary: almost all comparison operators (that is, all but
-is) return a Boolean value if the input to the operator (what’s on the left side) is a scalar. If we use a collection as input, then we are returned a list of matches. As an example:
"This","Test","tesT" -contains "test" returns
"This","Test","tesT" -like "test" returns
To know more, don’t forget to check the documentation: