Skip to content

inline head fast path silently defaults invalid/missing/negative -n to 10 lines (flag parsing) #708

Closed

Description

@caomengxuan666

Summary

The inline head pipeline fast path (src/executor/pipeline_exec.rs:2865)
hand-rolls its option scan: it skips any unknown -… word, then calls
head_line_count(&args).unwrap_or(10) (pipeline_exec.rs:3383). A malformed
count is therefore silently treated as "first 10 lines" with rc 0 instead of
an error, and a valid GNU negative count (-n -1, "all but the last line") is
lost because "-1".parse::<usize>() fails.

Classification: flag parsing. The arm should decline (→ external) whenever
the count operand is not a plain non-negative integer, rather than defaulting.

Minimal repro

$ niu -c "printf 'a\nb\nc\n' | head -n abc"; echo rc=$?
a
b
c
rc=0
$ <install>/winuxcmd/usr/bin/head.exe -n abc   # rc=1: head: invalid number of lines: 'abc'
$ D:/Git/bin/bash.exe -c "printf 'a\nb\nc\n' | head -n abc"   # rc=1, same message
repro niu fast external / GNU
printf 'a\nb\nc\n' | head -n abc a\nb\nc\n rc 0 error, rc 1
printf 'a\nb\nc\n' | head -n -1 a\nb\nc\n a\nb\n
printf 'a\nb\nc\n' | head -x a\nb\nc\n rc 0 head: invalid option -- 'x', rc 1
printf 'a\nb\nc\n' | head -n a\nb\nc\n rc 0 head: option requires an argument -- 'n', rc 1
printf 'a\nb\nc\n' | head --lines a\nb\nc\n rc 0 head: option '--lines' requires an argument, rc 1

Inside a command substitution the same arm runs through the real executor:

$ niu -c "x=\$(printf 'a\nb\nc\n' | head -n -1); printf '%s' \"\$x\""
a
b
c                            # GNU: a\nb

Suggested fix

Only take the inline path for -n N / -nN / --lines=N / -N with a valid
usize, and decline on -…/missing operand, so malformed shapes reach the real
head. The dormant tail arm in command_substitution_values.rs:128 reuses
head_line_count and would inherit the same defect if revived.

Found by the fast-path differential audit (#706).

Activity

  1. added
    bug
    area:fastpath
    on Oct 17, 2026
  2. caomengxuan666 commented on Oct 17, 2026

    @caomengxuan666
    MemberAuthor

    已在 d4f0b67(PR #718)修掉,只是 issue 没跟着关。当前 master d248d9f 复验(精确取 rc,不经管道):

    形态 rubash GNU
    printf 'a\nb\nc\n' | head -n abc rc 1,无输出 rc 1
    ... | head -n -1 rc 0,a\nb\n 同
    ... | head -x rc 1 同
    ... | head -n rc 1 同
    ... | head --lines rc 1 同
    ... | head -2 rc 0,a\nb\n 同

    非法/缺失操作数现在 decline 到真 head,负数走 GNU 的"除末尾 N 行"语义。剩下唯一的差别是诊断前缀带完整路径(/usr/bin/head: vs head:),那是外部命令 argv[0] 的另一件事,不在这个 issue 范围。

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

    area:fastpathbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions