简体   繁体   English

什么是bash中的@(... | ... | ...)语法?

[英]What is @(…|…|…) syntax in bash?

To focus on the @() syntax mentionned in this question : 重点关注这个问题中提到的@()语法:

[[ $OSTYPE == *@(darwin|freebsd|solaris|cygwin|openbsd)* ]]

Where does this syntax come from ? 这种语法来自哪里? Why is it used in this case ? 为什么在这种情况下使用它? And what is the difference with : 和有什么区别:

[[ $OSTYPE =~ (darwin|freebsd|solaris|cygwin|openbsd) ]]

or 要么

[[ $OSTYPE == *(darwin|freebsd|solaris|cygwin|openbsd) ]]

that all seems equivalents. 这似乎都是等价的。

Is this syntax used in place of the =~ operator for better portability with regex ? 是否使用此语法代替=~运算符以便使用正则表达式实现更好的可移植性?

Thanks for your clarifications 谢谢你的澄清

Search for the extglob option in man bash : man bash搜索extglob选项:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. 如果使用内置shopt启用了extglob shell选项,则会识别多个扩展模式匹配运算符。 In the following description, a pattern-list is a list of one or more patterns separated by a | 在以下描述中,模式列表是由|分隔的一个或多个模式的列表 . Composite patterns may be formed using one or more of the following sub-patterns: 可以使用以下子模式中的一个或多个来形成复合图案:

 ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns 

This uses rules explained in the Pattern Matching section of man bash : 这使用了man bashPattern Matching部分中解释的规则:

[[ $OSTYPE == *@(darwin|freebsd|solaris|cygwin|openbsd)* ]]

This uses regular expressions to perform the matching: 这使用正则表达式来执行匹配:

[[ $OSTYPE =~ (darwin|freebsd|solaris|cygwin|openbsd) ]]

These are very different mechanisms, with different performance implications. 这些是非常不同的机制,具有不同的性能影响。 There are no patterns in the values darwin , freebsd , ..., these are simple literal strings. darwinfreebsd ,...中没有模式,这些是简单的文字字符串。 The @(...) syntax is perfect for such simpler matching logic, so using regular expressions seems overkill. @(...)语法非常适合这种更简单的匹配逻辑,因此使用正则表达式似乎有点过分。

In this example both writing styles give the same behavior, it's just that they perform the matching through different mechanisms. 在这个例子中,两种写作风格都给出了相同的行为,只是它们通过不同的机制执行匹配。 If instead of a list of literal strings like darwin , freebsd , ... you had more complex regex patterns, then the first writing style wouldn't be an option, you would need to use the second version with full regex power. 如果不是像darwinfreebsd这样的文字字符串列表......你有更复杂的正则表达式模式,那么第一种写作风格就不是一种选择,你需要使用具有完全正则表达能力的第二种版本。

Is this syntax used in place of the =~ operator for better portability with regex ? 是否使用此语法代替=~运算符以便使用正则表达式实现更好的可移植性?

It is used because it is good enough for the purpose, regex not needed. 使用它是因为它足够好用于此目的,不需要正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM