Skip to content

[BUG] head -n N on a redirected file consumes the rest of the file, so the next command in the group reads nothing #389

Open

Description

@strandly-the-agent

Checks

  • I have updated to the latest minor and patch version of Strands Shell (built from main at dbb6189)
  • I have checked the documentation and this is not expected behavior
  • I have searched ./issues and there are no duplicates of my issue

Binding

Rust

Strands Shell Version

0.0.0 (built from source, main dbb6189, cargo build --release)

Language Runtime Version

Rust 1.100.0

Operating System

Debian 12 (aarch64)

Installation Method

built from source

Steps to Reproduce

$ strands-shell -c 'printf "1\n2\n3\n4\n5\n" > /tmp/in; { head -n 1; cat; } < /tmp/in'
$ strands-shell -c 'printf "1\n2\n3\n4\n5\n" > /tmp/in; { head -n 1; while read -r l; do echo "got $l"; done; } < /tmp/in'

Expected Behavior

As in bash 5.2.15 with GNU head: head -n 1 takes one line and the next command reads the rest.

1
2
3
4
5
1
got 2
got 3
got 4
got 5

Actual Behavior

Both commands print only 1, with exit status 0. The lines after the first are lost without a message.

Additional Context

Found while reviewing #378; that PR does not change this (same output at its head 3cde1aa). head -c is not affected since #307: { head -c 2; cat; } < /tmp/in prints the whole file, as in bash.

This is only about a redirected file. From a pipe, bash loses the rest too (printf "1\n2\n3\n4\n5\n" | { head -n 1; cat; } prints 1 in both), because GNU head cannot seek back on a pipe.

The line path wraps stdin in a BufReader, which takes more than the lines it prints and is dropped with those bytes still in it (src/commands/head.rs:74 at dbb6189). The caller then puts the reader back on fd 0 without them (src/commands/head.rs:50-52):

let mut reader = io::stdin()?;
let status = write_head(&mut reader, n, bytes, all_but_last, &mut w).await;
io::with_process(|p| p.restore_fd(0, reader.into_fd_kind()));

Possible Solution

After the last line is written, put the bytes still held by the BufReader (reader.buffer()) back at the front of the ChannelReader's unread bytes before restoring fd 0, as read does on a timeout (src/builtins/read.rs:109-115).

Related Issues

#307, #378

Activity

  1. added
    bug
    on Nov 21, 2026
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

    bug

    Type

    Fields

    Language

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions