在使用bash版本3的服务器中,我这样做:
bash3$e="tar xfz"; [[ "$e" =~ "^tar" ]] && echo 0 || echo 1 0
但是当我在bash版本4中执行相同的命令时
bash4$e="tar xfz"; [[ "$e" =~ "^tar" ]] && echo 0 || echo 1 1
我在CentOS,Fedora和Ubuntu中尝试过它并得到了相同的结果.怎么了?
解决方法
引用
Greg’s Wiki中正则表达式的部分:
Before 3.2 it was safe to wrap your regex pattern in quotes but this has changed in 3.2. Since then,regex should always be unquoted.
这是使用=〜最兼容的方式:
e='tar xfz' re='^tar' [[ $e =~ $re ]] && echo 0 || echo 1
这应该适用于两个版本的bash.