为什么不能字符串在bash定期EX pression测试使用? [英] Why can't string literals be used in bash regular expression tests?

查看:153
本文介绍了为什么不能字符串在bash定期EX pression测试使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下bash脚本只打印出变量工作

Why does the following bash script only print out variable worked?

#! /bin/bash

foo=baaz
regex='ba{2}z'

if [[ $foo =~ 'ba{2}z' ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

是不是有什么bash的文件中,指出 =〜运营商只能用于变量,而不是文字作品?这是否限制适用于任何其他操作?

Is there something in the bash documentation that states the =~ operator only works with variables, not literals? Does this limitation apply to any other operators?

推荐答案

您不需要为bash的正则表达式的报价了:

You don't need quotes for bash regex anymore:

#! /bin/bash

foo=baaz
regex='ba{2}z'

if [[ $foo =~ ba{2}z ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

# Should output literal worked, then variable worked

我不记得是哪个版本改变了这种虽然。

I can't remember which version changed this though.

这篇关于为什么不能字符串在bash定期EX pression测试使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆