grep '.*[s]' file


grep .*[s] file

Why do you need quotation marks to let this work properly? In the second case, grep seems trying to inspect every file with a period.

  • 4
    As a rule of thumb: you should always pass pattern to grep in single quotes unless you really knows what you are doing and why not to. – jimmij Jan 25 '15 at 11:13
  • @jimmij Just single quotes? Why not double quotes? – Hashim Sep 18 '18 at 23:17
  • 1
    @Hashim Because the content of single quotes are treated literally by the shell, but double quoted expressions are evaluated, e.g. variables are expanded. – jimmij Sep 19 '18 at 2:02
  • @jimmij Wow, I didn't know that. Thanks! – Hashim Sep 19 '18 at 23:24

Quotes (either single or double) around an argument inhibit glob expansion.

Your first example passes a Regular Expression as an argument to grep. Your second example contains a glob pattern which the shell itself expands, passing filenames that fit that pattern as arguments to grep.

  • So the glob pattern expands itself to all files in the current directory? – John H. K. Jan 25 '15 at 11:08
  • @JohnH.K.: Almost. It expands to all file names that begin with a dot . and end with an s. If you did .*[Ss] it would expand to file names that begin with a dot . and end with either S or s. – PM 2Ring Jan 25 '15 at 11:11
  • 1
    FWIW, when using globs I find it helpful to test them with echo or even better printf "%s\n" before plugging the glob into the actual command I want to run, just to make sure I haven't done something dumb. :) – PM 2Ring Jan 25 '15 at 11:13
  • A simple glob expands to match files in the current directory, but you can do things like ../*.txt which will expand to the file names ending in .txt in the parent directory. – PM 2Ring Jan 25 '15 at 11:17

Compare also:

echo '.*[s]' file


echo .*[s] file

This outputs the arguments as seen by the command.

In your first example you pass your grep command exactly two arguments: the pattern and the file.

In your second example your shell will handle the first argument and replace it with all the files starting with a dot and ending in "s". Therefore your grep command will get multiple arguments and it will try to find the first (expanded) filename in all other expanded filenames and the explicitly specified file.

  • Alternatively you can also use set -x to see all your commands as they are executed. – michas Jan 25 '15 at 11:33

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.