bsdgrep: Allow "-" to be passed to -f to mean "standard input"

A version of this patch was originally sent to me by se@, matching behavior
from newer versions of GNU grep.

While there have been some differences of opinion on whether stdin should be
closed or not after depleting it in process of -f, I've opted to leave stdin
open and just let the later matching stuff fail and result in a no-match.
I'm not married to the current behavior- it was generally chosen since we
are adopting this in particular from GNU grep, and I would like to stay
consistent without a strong argument to the contrary. The current behavior
isn't technically wrong, it's just fairly unfriendly to the developer-user
of grep that may not realize their usage is trivially invalid.

Submitted by:	se
This commit is contained in:
Kyle Evans 2018-05-08 03:53:46 +00:00
parent 10d20c84ed
commit 24a656c291
2 changed files with 13 additions and 3 deletions

View File

@ -30,7 +30,7 @@
.\"
.\" @(#)grep.1 8.3 (Berkeley) 4/18/94
.\"
.Dd April 25, 2018
.Dd May 7, 2018
.Dt GREP 1
.Os
.Sh NAME
@ -404,6 +404,13 @@ and block buffered otherwise.
.El
.Pp
If no file arguments are specified, the standard input is used.
Additionally,
.Dq -
may be used in place of a file name, anywhere that a file name is accepted, to
read from standard input.
This includes both
.Fl f
and file arguments.
.Sh EXIT STATUS
The
.Nm grep

View File

@ -307,7 +307,9 @@ read_patterns(const char *fn)
size_t len;
ssize_t rlen;
if ((f = fopen(fn, "r")) == NULL)
if (strcmp(fn, "-") == 0)
f = stdin;
else if ((f = fopen(fn, "r")) == NULL)
err(2, "%s", fn);
if ((fstat(fileno(f), &st) == -1) || (S_ISDIR(st.st_mode))) {
fclose(f);
@ -324,7 +326,8 @@ read_patterns(const char *fn)
free(line);
if (ferror(f))
err(2, "%s", fn);
fclose(f);
if (strcmp(fn, "-") != 0)
fclose(f);
}
static inline const char *