您的位置:首页 > 运维架构 > Shell

Bash 4.1条件正则表达式与3.1的改变之处

2012-11-22 21:58 176 查看
工作中,同一脚本在bash 3.1下执行成功,但在4.1环境下失败。

查询相关资料,发现是3.2版本新增的特性:

f.  Quoting the string argument to the [[ command's  =~ operator now forces
string matching, as with the other pattern-matching operators.


引用会把正则表达式直接看作字符串:

[vimos@vimos 015 Bash]$ [[ "HEllo" =~ "^([[:upper:]]{2}[[:lower:]]*$)" ]] && echo match || echo no
no
[vimos@vimos 015 Bash]$ [[ "HEllo" =~ ^([[:upper:]]{2}[[:lower:]]*$) ]] && echo match || echo no
match
[vimos@vimos 015 Bash]$ [[ "^([[:upper:]]{2}[[:lower:]]*$)" =~ "^([[:upper:]]{2}[[:lower:]]*$)" ]] && echo match || echo no
match


当前有两种处理方式,可以解决这个问题:

将正则表达式声明为变量:

本例子来源于网络:

[vimos@vimos 015 Bash]$ REG="^([[:upper:]]{2}[[:lower:]]*$)";[[ "HEllo" =~ $REG ]] && echo match || echo no
match


采用3.1兼容模式运行
[vimos@vimos 015 Bash]$ shopt -s compat31
[vimos@vimos 015 Bash]$ [[ "HEllo" =~ "^([[:upper:]]{2}[[:lower:]]*$)" ]] && echo match || echo no
match

去除兼容模式

[vimos@vimos 015 Bash]$ shopt -u compat31
[vimos@vimos 015 Bash]$ [[ "HEllo" =~ ^([[:upper:]]{2}[[:lower:]]*$) ]] && echo match || echo no
match
[vimos@vimos 015 Bash]$ [[ "HEllo" =~ "^([[:upper:]]{2}[[:lower:]]*$)" ]] && echo match || echo no
no


参考文章:

【1】http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression

【2】http://tiswww.case.edu/php/chet/bash/NEWS

【3】bash: regular-expression comparaison (=~) no longer works.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: