Search code examples
bashgrepecho

Using wildcard in bash-variable for echo and grep


I am trying to come up with a function that searches a given file for a given pattern. If the pattern is not found it shall be appended to the file.

This works fine for some cases, but when my pattern includes special characters, like wildcards (*) this method fails.

Patterns that work:
pattern="some normal string"

Patterns that don't work:
pattern='#include "/path/to/dir/\*.conf"'

This is my function:

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

I' calling my function like this:
check_pattern $pattern $target_file

When escaping the wildcard in my pattern variable to get grep running correctly echo interprets the \ as character.

So when I run my script a second time my grep does not find the pattern and appends it again.

To put it simple: Stuff that gets appended:
#include "/path/to/dir/\*.conf"

Stuff that i want to have appended:
#include "/path/to/dir/*.conf"

Is there some way to get my expected result without storing my echo-pattern in a second variable?


Solution

  • Thanks all, I got it now.

    Using grep -F as pointed out by Gem Taylor in combination with calling my function like this check_pattern "$pattern" "$target_file" did the tricks.