Skip to content

grep - POSIXLY_CORRECT is ignored: options after the first operand are still parsed #183

Open

Description

@sylvestre

GNU grep documents that when POSIXLY_CORRECT is set (to any value, even empty), options
that follow file names are treated as file names, as POSIX requires; without it, options are
permuted to the front. uu_grep never reads the variable and always permutes, so
POSIXLY_CORRECT=1 grep foo t -i applies -i instead of reporting a missing file -i.
This also applies to a trailing -NUM, -c, -e, --, etc. Without the variable both
tools behave the same.

Reproduction

Rust (incorrect)

$ printf 'Foo\n' > t
$ POSIXLY_CORRECT=1 ./target/release/grep foo t -i
Foo
# Exit code: 0

GNU (correct)

$ POSIXLY_CORRECT=1 LC_ALL=C /usr/bin/grep foo t -i
/usr/bin/grep: -i: No such file or directory
# Exit code: 2

(GNU manual, "Environment Variables": "If set, grep behaves as POSIX requires ... POSIX
requires that options that follow file names must be treated as file names; by default, such
options are permuted to the front of the operand list and are treated as options."
)

Root cause

Nothing in src/ reads POSIXLY_CORRECT. The positional arg in uu_app()
(src/lib.rs:510) is a plain multi-value positional, so clap accepts flags anywhere, and the
expand_num_shorthand pre-pass (src/lib.rs:863) skips over operands and keeps rewriting
later -NUM arguments:

// Narrow down to `-flags` (and `--options`) and strip the leading `-` for easier matching.
let Some(arg) = arg.strip_prefix(b"-") else {
    // Not a flag, skip.
    i += 1;
    continue;
};

Test

#[test]
fn posixly_correct_stops_at_first_operand() {
    let (scene, mut c) = ucmd();
    scene.fixtures.write("in", "Foo\n");
    c.env("POSIXLY_CORRECT", "1")
        .args(&["foo", "in", "-i"])
        .fails_with_code(2)
        .no_stdout()
        .stderr_contains("-i: No such file or directory");

    let (scene, mut c) = ucmd();
    scene.fixtures.write("in", "Foo\n");
    c.env("POSIXLY_CORRECT", "")
        .args(&["-c", "Foo", "in", "-3"])
        .fails_with_code(2)
        .stdout_is("in:1\n")
        .stderr_contains("-3: No such file or directory");

    // Without the variable, trailing options still apply.
    let (scene, mut c) = ucmd();
    scene.fixtures.write("in", "Foo\n");
    c.args(&["foo", "in", "-i"]).succeeds().stdout_only("Foo\n");
}

Reported by Anthropic's OSS Scanner (ANT-2026-NWETH7YQ).

Activity

  1. added
    good first issue
    oss-scanner
    gnu-compat
    on Nov 9, 2026
  2. added a commit that references this issue on Nov 25, 2026
    e24f4e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    gnu-compatgood first issueoss-scanner

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions