Grep Quotes Usage – When to Use Single, Double, or No Quotes

commandgrepshellunixunix-shell

While trying to search for a simple pattern "hello" in a file, all the following forms of grep work:

  • grep hello file1
  • grep 'hello' file1
  • grep "hello" file1

Is there a specific case where one of the above forms work but others do not.
Does it make any difference if I use one in place of another?

Best Answer

This is actually dependent on your shell. Quotes (either kind) are primarily meant to deal with whitespace. For instance, the following:

grep hello world file1

will look for the word "hello" in files called "world" and "file1", while

grep "hello world" file1

will look for "hello world" in file1.

The choice between single or double quotes is only important if the search string contains variables or other items that you expect to be evaluated. With single quotes, the string is taken literally and no expansion takes place. With double quotes, variables are expanded. For example (with a Bourne-derived shell such as Bash or ZSH):

VAR="serverfault"
grep '$VAR' file1
grep "$VAR" file1

The first grep will look for the literal string "$VAR1" in file1. The second will expand the "$VAR" variable and look for the string "serverfault" in file1.

Related Topic