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

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

if [[ '443089607' =~ ^[0-9]*$ ]]; then echo 'match'; else echo 'not match'; fi
if [[ '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'; fi
if expr 'huzhenghui' : ^[0-9]*$; then echo 'match'; else echo 'not match'; fi

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

expr: warning: '^[0-9]*$': using '^' as the first character
of 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'; fi
if expr 'huzhenghui' : [0-9]*$; then echo 'match'; else echo 'not match'; fi

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值