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 <>


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 ...
  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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