diff --git a/src/lib.rs b/src/lib.rs index 47baca7..690953e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -419,6 +419,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { }; let matcher = Matcher::compile(&config)?; + + // grep with -m 0 should not open any file + if config.max_count == Some(0) { + return Err(ExitCode::new(1)); + } + // An empty pattern matches every line; with `-v`, GNU grep selects no lines // and exits as "no match" without reading any input files. if invert_match && patterns.iter().any(|pattern| pattern.is_empty()) { diff --git a/tests/test_grep.rs b/tests/test_grep.rs index 804c816..d612a40 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -432,6 +432,21 @@ fn max_count() { .fails_with_code(1) .no_stdout(); + let (_s, mut c) = ucmd(); + c.args(&["-m", "0", "a", "missing"]) + .fails_with_code(1) + .no_output(); + + let (_s, mut c) = ucmd(); + c.args(&["-m", "1", "a", "missing"]) + .fails_with_code(2) + .stderr_contains("grep: missing:"); + + let (_s, mut c) = ucmd(); + c.args(&["-m", "0", "-e", "["]) + .fails_with_code(2) + .stderr_contains("invalid pattern"); + // -A trailing context still printed after the cutoff. let (_s, mut c) = ucmd(); c.args(&["-m", "1", "-A", "2", "match"])