Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I store downloaded files in a log like this:

[source] filename

To avoid downloading a file more than once I grep for [source] filename before:

if ! grep "$signature" downloaded.log > /dev/null; then
    wget ...

but starting my line with [ grep does not work the way I need:

signature="[source] filename"
echo $signature | grep "$signature"
echo $signature | grep "\$signature" #trying to escape first bracket

both return nothing.

Any smart workaround?

It would be nice also having no need to change the code switching to parens (), braces {}, or whatever <>

share|improve this question
up vote 5 down vote accepted

First you have to quote your variable, then you should use -F --fixed-strings switch to avoid interpreting the brackets as regular expression meta characters:

echo "$signature" | grep -F "$signature"

Then you should also use -q --quiet switch too, so grep exit as soon as found the first occurrence. This only for speed consideration:

if ! grep -Fq "$signature" downloaded.log; then
    wget ...
share|improve this answer
Thank you, I'm going to test it. You are right about quoting variables, just forgot them writing question – neurino Oct 21 '11 at 15:15
@neurino One more thing: you should add the -x (match whole line) option to grep, otherwise a line like [foo] I say [source] filename, so there! will match. Note that this means [source] filename2 won't match (definitely desirable), nor will [source] filename was read (may or may not be desirable). – Gilles Oct 21 '11 at 16:41
@Gilles: -x option is definitely desirable, thank you very much – neurino Oct 21 '11 at 18:15

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.