$man bash
Word splitting and filename expansion are not performed on the words between the ‘[[’ and ‘]]’; tilde expansion,parameter and variable expansion,arithmetic expansion,command substitution,process substitution,and quote removal are performed.
$echo $BASH_VERSION 4.2.10(1)-release
命令1
$[[ "hello" =~ "he" ]] && echo YES || echo NO YES
命令2
$[[ "hello" =~ he.* ]] && echo YES || echo NO YES
命令3
$[[ "hello" =~ "he.*" ]] && echo YES || echo NO NO
为什么命令2和3不同?
检查你的bash版本.从版本3.2开始,添加了以下状态:
Quoting the string argument to the [[ command’s =~ operator now forces
string matching,as with the other pattern-matching operators.
我猜你正在使用bash> = ver 3.2进行测试.
这就是你引用正则表达式的原因,它正在进行简单的字符串匹配而不是正则表达式匹配.
更新:如果你想在双引号内匹配正则表达式,那么使用:
shopt -s compat31
根据手册:
compat31
If set,bash changes its behavior to that of version 3.1
with respect to quoted arguments to the conditional command’s =~ operator.
这会导致您的命令行为不同:
[[ "hello" =~ "he.*" ]] && echo YES || echo NO YES