26

When I type "grep doc" in the terminal, it just don't do anything, stopping the terminal from doing anything else before I escape using Ctrl+C or Z.

I know this isn't how I'm supposed to use grep, but just curious why this is happening.

41

grep by default searches standard input if no files are given:

grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

If you just do grep doc grep expects standard input to come and search inside it (don't enter parts between < and > into the terminal, these are comments):

$ grep doc
a b c <PRESS ENTER HERE>
doc <NO MATCH WAS FOUND IN PREVIOUS LINE, TYPE doc AND PRESS ENTER AGAIN>
doc <MATCH WAS FOUND>
  • 7
    OP can also press Ctrl+D on a line by itself to end the grep "session." – Kevin Mar 26 '15 at 18:26
  • 2
    Good answer. Just wanted to note that pretty much no one ever needs to use grep by typing like that, but it allows you to pipe standard output from a previous command, which is very useful. – Karl Bielefeldt Mar 27 '15 at 1:17
  • 20
    @KarlBielefeldt: It's actually a convenient way to debug complicated regexps. You can run something like grep '([a-z]+[0-9]*.x){2,3}' and type a bunch of sample lines on your keyboard to make sure it matches what you think it does. Lines that match will be echoed, lines that don't will not. – Nate Eldredge Mar 27 '15 at 6:10
  • 1
    @NateEldredge: Thanks for giving a practical example for this! I'd always looked at null-arg invocations of things like grep and cat as being mainly theoretical. – labyrinth Mar 27 '15 at 14:04
  • 1
    @labyrinth They're not theoretical at all, they're used all the time when piping, e.g. somecommand | grep foo – Barmar Apr 1 '15 at 18:21
15

grep is waiting for input.

From man grep:

[...]
DESCRIPTION
       grep  searches  the named input FILEs (or standard input if no files are named
[...]

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.