0

given the following code:

x="my_string123"
# 1)
if [[ "${x}" = "my_s"* ]] ; then
    echo "YES"
else
    echo "NO"
fi
# 2)
if test "${x}" == "my_string123" ; then
    echo "YES"
else
    echo "NO"
fi
# 3)
if test "${x}" == "my_str"* ; then
    echo "YES"
else
    echo "NO"
fi

I get this output:

YES
YES
NO

But i not sure why i get from the last "NO".
After all, I used regex * and therefore I would expect to get YES. What am I missing here?

  • 1
    Because the `test` builtin implements the behavior of `[`, not of `[[`, and does not support regular expression matching. – larsks Mar 20 '23 at 19:55
  • 1
    Mind, you aren't doing regex matching even with `[[`. The `=` operator is glob matching, not regex matching. `*` in a regex has a different meaning ("zero-or-more of the preceding symbol"); it doesn't mean "match anything here". – Charles Duffy Mar 20 '23 at 19:58
  • 1
    You may want to read [BashFAQ/31](https://mywiki.wooledge.org/BashFAQ/031) – M. Nejat Aydin Mar 20 '23 at 19:58
  • Anyhow, if what you really wanted to know is how to do glob matching against a string in a shell without `[[`, the answer is to use `case`, not `test`. – Charles Duffy Mar 20 '23 at 19:59
  • (Also, note that `test` isn't required to support `==` at all; [the standardized string comparison operator is `=`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html); any examples you see using `==` are bad form, using extensions that reduce compatibility without providing any practical benefit in return). – Charles Duffy Mar 20 '23 at 20:07

0 Answers0