bash what means quotes inside asterisk *"str"*

I have an example

o="o"
if [[ *"aoei"* == $o ]]; then echo 5; fi;

What means asterisk in this example?

p.s. is order important? if [[ *"o"* == $o ]] vs if [[ $o == *"o"* ]]

2

1 Answer

Order is crucial. As documented for the [[ conditional construct, the == operator is a pattern matching operator where the right-hand side is a glob pattern (aka "wildcard").

  • [[ *"o"* == $o ]] tests if the literal string *o* matches the pattern contained in the variable $o
  • [[ $o == *"o"* ]] tests if the string contained in the variable $o matches the pattern *o* (i.e. if the contents of $o contains an o)

Note that the pattern *"aoei"* means: zero or more of any character, followed by the exact sequence aoei, followed by zero or more of any character. Perhaps you intended the pattern *[aoei]* which means: contains an a or an o or an e or an i.

Demonstrating:

$ o="o"
$ if [[ *"aoei"* == $o ]]; then echo 5; fi; # no output
$ if [[ $o == *"aoei"* ]]; then echo 5; fi; # no output
$ o="AaoeiBC"
$ if [[ *"aoei"* == $o ]]; then echo 5; fi; # no output
$ if [[ $o == *"aoei"* ]]; then echo 5; fi;
5
$ o="o"
$ if [[ *[aoei]* == $o ]]; then echo 5; fi; # no output
$ if [[ $o == *[aoei]* ]]; then echo 5; fi;
5
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like