看了rhel5.5的bash(3.2.25)的资料,对"=~"怎么用感到困惑
# match the IP, and return true
[kevin@server1 shell]# [[ 192.168.1.1 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
ok
# add double qoute
# return false, en ... I know.
[kevin@server1 shell]# [[ 192.168 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
fail
# remove double qoute
# return ture ? Why ?
[kevin@server1 shell]# [[ 192.168 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo ok || echo fail
ok
那么,我应该把字符串放在运算符右边吗?
为什么第二个命令返回true,按理说应该返回false!
信息如下:
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 regex3)). 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' (see the description ofshopt' in *Note Bash Builtins::) is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable
BASH_REMATCH'. The element ofBASH_REMATCH' with index 0 is the portion of the string matching the entire regular expression. The element of
BASH_REMATCH' with index N is the portion of the string matching the Nth parenthesized subexpression.
最佳答案
推荐的、最广泛兼容的处理正则表达式模式的方法是用单引号单独声明它们:
$ re='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
$ [[ 192.168.1.1 =~ $re ]] && echo ok || echo fail
ok
$ [[ 192.168 =~ $re ]] && echo ok || echo fail
fail
可以在 Greg's Wiki 上找到关于 bash 版本行为差异的一些讨论。 - 关键信息是使用不带引号的变量是最好的方法。
关于regex - 如何使用 bash(3.2.25) 的一个额外的二元运算符 :=~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730879/