Why can't string literals be used in bash regular expression tests?

限于喜欢 提交于 2019-12-12 10:39:45

问题


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

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?


回答1:


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.




回答2:


Your code actually works as expected up until Bash 3.1. But since Bash 3.2 the behavior of the pattern match operator has been changed. Quote from the latest Bash Manual:

“Any part of the pattern may be quoted to force it to be matched as a string.“

And that is exactly what is happening here. You meant to use {} as meta characters, but since you quoted it Bash interprets them literally. You have two options.:

1.You can turn on the 3.1 compatibility mode with shopt -s compat31 like this:

#!/bin/bash
shopt -s compat31

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

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

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

2.You can port your code, by removing the quotations from the right hand side of the operator:

#!/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


来源:https://stackoverflow.com/questions/6665529/why-cant-string-literals-be-used-in-bash-regular-expression-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!