0

I am new at unix, I'm trying to learn the bash language, and when I went to the "Testing expression", I found this one:

[[ "whatever" =~ h[aeiou] ]] 

I already read the answer to this question, so I understand what the operator =~ does. After running the previous command, the output of echo $? is 0, meaning the condition inside the [[ ]] is met. If instead I type

[[ "whatever" =~ h[sdfghjkl] ]] 

the output of echo $? is 1, so the condition was not met.

So, I would like to know what the h[aeiou] and h[sdfghjkl] are. Is h a predefined function inside the [[ ]] expression? And if so, what is it doing? If not, what h[aeiou] and h{sdfghjkl] actually are?

Thanks.

2
  • Your first command will evaluate as true if the string "whatever" contains the letter h followed by a vowel. Second command looks for h followed by your list of letters. h is not a predefined function but is part of the regular expression to match against. Commented Oct 11, 2022 at 20:33
  • They are regular expressions. h[aeiou] matches a pair of letters, the left letter being h and the right-hand letter being one of those listed between [ and ] (an English vowel letter). h[sdfghjkl] is exactly the same, but with matching the right-hand letter with a list of different letters between [ and ]. Commented Oct 11, 2022 at 20:33

1 Answer 1

2

Like it says in the other post, the =~ does a pattern match, with the right-side operand being a regular expression (regex).

The brackets in h[aeiou] are part of the regex syntax, there's no named function there. h[aeiou], matches an h and then any single one of aeiou, so whatever matches because it contains an h followed by an a.

You're going to hear about regexes, so it might be worth looking into them a bit:

(The Wikipedia page seems to also go in the formal details, don't get too caught up in that.)

2
  • Thanks for the quick answer! It solved my question, and thanks for the provided links. :] Commented Oct 11, 2022 at 20:58
  • @andr.lex, note that =~ doesn't require a full-string match, so indeed [[ whatever =~ h[aeiou] ]] matches. That's unlike most contexts where shell patterns are used. (The original version of this answer, before terdon fixed it, said it wouldn't match, and I don't know what I was thinking there.) Commented Oct 12, 2022 at 17:27

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.