Linux shell 脚本中“=~”运算符的含义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12454731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:22:18  来源:igfitidea点击:

Meaning of "=~" operator in shell script

regexlinuxbashshell

提问by cc4re

I came across a shell script where the code is

我遇到了一个 shell 脚本,其中的代码是

for line in $LIST_ARRAY;do
if [[ $LIST_ARRAY =~ $line ]]
then
echo "true"
....
...
.

What is the use of =~in this case?

什么是使用=~在这种情况下?

采纳答案by MimiEAM

it's the Equal Tilde operator that allows the use of regex in an if statement.

它是 Equal Tilde 运算符,它允许在 if 语句中使用正则表达式。

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string.

可以使用额外的二元运算符 =~,其优先级与 == 和 != 相同。使用时,运算符右侧的字符串被视为扩展正则表达式并进行相应匹配(如 regex(3) 中所示)。如果字符串与模式匹配,则返回值为 0,否则为 1。如果正则表达式在语法上不正确,则条件表达式的返回值为 2。如果启用了 shell 选项 nocasematch,则执行匹配时不考虑字母字符的大小写。可以引用模式的任何部分以强制将其作为字符串进行匹配。

http://linux.die.net/man/1/bash

http://linux.die.net/man/1/bash