在 bash 变量中使用通配符进行 echo 和 grep

Using wildcard in bash-variable for echo and grep

我正在尝试想出一个函数来搜索给定文件的给定模式。如果未找到模式,则应将其附加到文件中。

这在某些情况下工作正常,但当我的模式包含特殊字符时,如通配符 (*),此方法失败。

有效的模式:
pattern="some normal string"

无效的模式:
pattern='#include "/path/to/dir/\*.conf"'

这是我的功能:

check_pattern() {
    if ! grep -q "" 
    then
        echo  >> 
    fi
}

我这样调用函数:
check_pattern $pattern $target_file

在我的模式变量中转义通配符以正确获取 grep 运行ning 时 echo\ 解释为字符。

因此,当我第二次 运行 我的脚本时,我的 grep 没有找到模式并再次附加它。

简单来说: 附加的内容:
#include "/path/to/dir/\*.conf"

我想附加的东西:
#include "/path/to/dir/*.conf"

有没有什么方法可以在不将我的 echo 模式存储在第二个变量中的情况下获得我的预期结果?

谢谢大家,我明白了

如 Gem Taylor 所指出的,使用 grep -F 并结合这样调用我的函数 check_pattern "$pattern" "$target_file" 就达到了目的。

使用

grep -f

check_pattern "$pattern" "$target_file"