Skip to content

[BUG] $? reads 0 in a command piped into a loop, group or subshell (false; echo "$?" | while read … prints 0) #381

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)

Language Runtime Version

Rust 1.100.0

Operating System

Debian 12 (aarch64)

Installation Method

built from source

Steps to Reproduce

$ strands-shell -c 'false; echo "first:$?" | { cat; }'
$ strands-shell -c 'false; echo "s:$?" | while read l; do echo "$l"; done'
$ strands-shell -c '( exit 3 ); echo "rc=$?" | if true; then cat; fi'

Expected Behavior

As in bash 5.2.15, $? is the status of the command before the pipeline: first:1, s:1, rc=3.

Actual Behavior

first:0, s:0, rc=0, with exit 0 and nothing on stderr. The same happens through Shell::run (a temporary differential case with the first script fails on stdout).

With a plain command on the right the value is correct:

$ strands-shell -c 'false; echo "first:$?" | cat'        # first:1
$ strands-shell -c 'false; { echo "first:$?"; } | cat'   # first:1

Additional Context

Found while reviewing #359. cmd | compound is parsed into a subshell that first defines the generated function and then runs the pipeline (parse_pipeline_into_compound, src/parser.rs:1602 at dbb6189). Defining a function sets the status to 0 (src/exec.rs:2452-2455):

Item::Function { name, body } => {
    proc.set_function(name, body.clone());
    Ok(0)
}

so every stage of the pipeline starts with $? = 0. #359 uses the same shape for compound | compound, so there false; { echo "first:$?"; } | { cat; } prints first:0 too.

Possible Solution

Keep the previous status when the function being defined is the generated _strands_compound. Returning the old status from that arm isn't enough on its own: under set -e a non-zero value there would end the script, so the definition also has to be exempt from the errexit check.

Related Issues

#359, #337

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