Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/searcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,12 @@ impl<'a> Searcher<'a> {
.flush()
.map_err_context(|| "(standard output)".to_string())?;

if self.had_error {
// With -q, a match yields exit status 0 even if an error (e.g. a
// missing file) occurred earlier: GNU exits as soon as a line is
// selected, so the error never affects the status.
if self.config.quiet && self.any_match {
Ok(())
} else if self.had_error {
Comment on lines +124 to +126
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about it some more, a shorter expression of the old code is had_error && !(quiet && any_match), but I'm not sure if that's any more readable.

Err(ExitCode::new(2))
} else if self.any_match {
Ok(())
Expand Down
22 changes: 22 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,28 @@ fn ere_invalid_pattern_is_error() {
.stderr_contains("invalid pattern");
}

#[test]
fn quiet_match_overrides_file_error() {
// With -q, a match makes grep exit 0 even if an earlier file could not be
// opened. Without -q the missing file still yields exit 2, and -q with no
// match keeps the error status.
let (_s, mut c) = ucmd();
c.args(&["-q", "abc", "no-such-file", "-"])
.pipe_in("abcd\n")
.succeeds()
.no_output();

let (_s, mut c) = ucmd();
c.args(&["abc", "no-such-file", "-"])
.pipe_in("abcd\n")
.fails_with_code(2);

let (_s, mut c) = ucmd();
c.args(&["-q", "zzz", "no-such-file", "-"])
.pipe_in("abcd\n")
.fails_with_code(2);
}

#[test]
fn initial_tab_skips_empty_lines() {
// -T aligns content with a tab, but GNU omits the tab for an empty line
Expand Down
Loading