教训:某款嵌入式Linux [[不支持=~正则表达式

来源:互联网 发布:php 前台框架 编辑:程序博客网 时间:2024/06/08 04:14

Linux Bash 脚本中,通常使用 [[ 判断正则表达式,例如判断非负整数。

if [[ '443089607' =~ ^[0-9]*$ ]]; then echo 'match'; else echo 'not match'; fiif [[ 'huzhenghui' =~ ^[0-9]*$ ]]; then echo 'match'; else echo 'not match'; fi

不过在某些嵌入式 Linux 中, [[ 不支持 =~ 正则表达式,返回错误信息:

sh: =~: unknown operand

此时,可以使用 expr

if expr '443089607' : ^[0-9]*$; then echo 'match'; else echo 'not match'; fiif expr 'huzhenghui' : ^[0-9]*$; then echo 'match'; else echo 'not match'; fi

不过可能会出现一个警告:

expr: warning: '^[0-9]*$': using '^' as the first characterof a basic regular expression is not portable; it is ignored

查看 info expr 可知:

‘STRING : REGEX’     Perform pattern matching.  The arguments are converted to strings     and the second is considered to be a (basic, a la GNU ‘grep’)     regular expression, with a ‘^’ implicitly prepended.  The first     argument is then matched against this regular expression.

其中 with a ‘^’ implicitly prepended 也就是开头隐含了^字符,不需要显式设置。应当写为:

if expr '443089607' : [0-9]*$; then echo 'match'; else echo 'not match'; fiif expr 'huzhenghui' : [0-9]*$; then echo 'match'; else echo 'not match'; fi

不说了,还有一大波的脚本需要逐个hack、调试……