Skip to content

fix: ignore set -e inside a body run left of && or || - #355

Open
ferdingler wants to merge 4 commits into
strands-agents:mainfrom
ferdingler:fix/259-errexit-tested-context
Open

ferdingler wants to merge 4 commits into
strands-agents:mainfrom
ferdingler:fix/259-errexit-tested-context

Conversation

@ferdingler

Copy link
Copy Markdown
Collaborator

Description

With set -e on, a failure inside a function, brace group, subshell or eval killed the whole script even when that body was on the left of || or &&. So f || echo caught never got to run the handler, and the script just exited 1. Bash ignores set -e for everything run in that position, so the body keeps going and the script carries on.

Now the left side of && and || ignores set -e all the way through whatever it runs, the same way ! already did. The last command of an &&/|| chain and plain untested calls still exit early, as in bash. Small change in the executor.

I added differential cases for function, group, subshell and eval bodies under ||, &&, if/while and !, a nested function call, and two cases that must still exit early. On main the ||, && and nested cases failed (the if and ! ones already matched bash). With the change they all match bash, and the full test suite passes.

Related Issues

Fixes #259

Documentation PR

N/A

Type of Change

Bug fix

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

@github-actions github-actions Bot added the bug Something isn't working label Nov 21, 2026

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The fix is right for the direct execution path, but it makes a child sh ignore its own set -e when it runs left of && or ||.

Finding Where
🔴 sh build.sh || handler: a set -e child script runs past its failure and exits 0 (regression) inline, src/exec.rs:2371
🟡 #259 still reproduces when the list's output is captured: $(f || h), { f || h; } > file, … done | cmd inline, src/exec.rs:2361

Both have a small fix that I checked in a scratch build. Everything else I threw at the counter held up.

What I verified, and non-blocking notes (5)

Verified (head 8aac37a, base dbb6189, debug builds, bash 5.2.15 as the reference)

  • cargo test --workspace --all-targets on head: 2733 passed, 0 failed.
  • The seven new .expected files match what bash prints. Three cases fail on base and pass on head (ignored_in_and_body, ignored_in_or_body, ignored_nested_tested_call); the other four pass on both and act as guards.
  • About 450 hand-written and 1,860 generated scripts compared across bash, base and head. Apart from the two findings and note 4, every difference on head is also on base.
  • The counter is restored after return, exit, break/continue, command-not-found, nounset errors, a failed eval or source, 2,000 loop iterations, 40-deep groups, and a Shell::run or MCP call that times out mid-body. No panics.
  • Function, group, subshell, eval and . bodies match bash left of ||, left of && and mid-chain. The last element, the right-hand side and the next statement still exit.
  • Not run: Python and Node bindings, release builds, cargo fmt/clippy (CI is green on those).

Reading order: src/exec.rs:2359-2374, then the child-shell setup at src/exec.rs:4221-4227, then the second loop at src/exec.rs:1954-1967.

Non-blocking

  1. Stale comments: src/os.rs:224 and src/shell.rs:420, :455 still describe the counter as counting ! only.
  2. Test gap: no case has control flow leave a tested body. A build that skips the decrement on the error path passes the whole suite. This case catches it (bash: no output, status 1):
    set -e
    for i in 1 2; do { false; break; } || echo x; done
    false
    echo unreachable
  3. Test gap: #259 names ./source bodies. They work on head (. ./lib.sh || echo caught) but no case covers them.
  4. Contrived edge, new on head: an explicit set -e inside a $( ) used as a for list, inside a tested function, is now ignored. set -e; g() { false; echo a; }; f() { for x in $(set -e; g); do echo "got $x"; done; echo f-end; }; f || echo c prints f-end on bash and base, got a then f-end on head.
  5. Same on base, so not part of this review and not filed:
    • set -e; { false; echo x; } > f.txt keeps going (bash exits 1): the capturing path never applies errexit to a compound.
    • set -e; for i in 1 2; do if break; then :; fi; done; false; echo unreachable prints unreachable: execute_if returns on ? at src/exec.rs:2685 before restoring opt_errexit.
    • if f where f runs set -e exits, because conditions zero opt_errexit instead of using the counter.
    • x=$(f) applies errexit inside f (bash turns it off in command substitutions).

Comment thread src/exec.rs
// Like `!`, a left side of && or || ignores errexit throughout its
// body, including function, group and eval bodies it runs.
let ignored = u32::from(and_or);
proc.errexit_ignored += ignored;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 A child sh left of && or || now ignores its own set -e

Process::fork() copies errexit_ignored (src/os.rs:597), and sh/lash children are built from a fork (src/exec.rs:4221). With this increment, sh build.sh || { echo "build failed"; exit 1; } runs the child with errexit ignored. A script that starts with set -e carries on past its failing command and exits 0, so the handler never runs and the outer script continues. On base and in bash the child stops and the handler runs. The outer script doesn't need set -e for this to happen.

Suggestion: reset the counter where the child shell is set up, and add a differential case such as sh -c 'set -e; false; echo no' || echo failed.

// src/exec.rs:4222, inside `if is_script {`
state_proc.errexit_ignored = 0;

With that line in a scratch build, the scripts below match bash and cargo test --workspace --all-targets passes (2733). It also fixes ! sh -c '…', which has had the same leak since #265.

Reproduction details

Head 8aac37a, base dbb6189, debug CLI builds run as strands-shell -c '<script>', aarch64 Linux. Reference: env -i PATH=/usr/bin:/bin LC_ALL=C bash -c '<script>' (bash 5.2.15) in an empty directory. Output is stdout, then exit status.

printf 'set -e\necho building\nfalse\necho "build ok"\n' > build.sh
sh build.sh || { echo "build failed"; exit 1; }
echo deploying
stdout status
bash building, build failed 1
base building, build failed 1
head building, build ok, deploying 0
Script bash and base head
sh -c 'set -e; false; echo child-continued' || echo child-failed child-failed, 0 child-continued, 0
sh build.sh && echo deploying (same build.sh) building, 1 building, build ok, deploying, 0
out=$(sh -c 'set -e; false; echo x') || echo c; echo "out=$out" c, out=, 0 out=x, 0

Control: sh -c 'set -e; false; echo x'; echo "after $?" (no connector) matches bash on both builds.

The same happens through lash -c, xargs sh -c, find -exec sh -c, and a sh call inside a function that is itself left of ||.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c63d8c8. The child shell now starts with the counter reset, so sh build.sh || handler, sh build.sh && … and ! sh -c … stop at the child's failure like bash. Added differential case set_e_child_sh_in_tested_context (failed on 8aac37a, passes now).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c63d8c8. The four scripts above and 16 more child-shell shapes (lash, xargs, find -exec, a shebang script, eval, nested sh, inside $( ) and redirected groups) now match bash.

Comment thread src/exec.rs
// Determine if this item is in a "tested" context (suppresses errexit).
// Tested = followed by && or ||, or inverted by `!`.
let tested = matches!(connector, Some(Connector::And) | Some(Connector::Or))
let and_or = matches!(connector, Some(Connector::And) | Some(Connector::Or));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The same list still exits early when its output is captured

run_capturing_status has its own &&/|| loop (src/exec.rs:1954-1967) that this change doesn't touch. It runs lists inside $( ), inside a compound with an output redirect, and inside a compound that feeds a pipe. In those places the #259 shape behaves on head exactly as on base. With set -e; f() { false; echo in-f; }:

  • { f || echo caught; } > out.txt; cat out.txt; echo after prints nothing and exits 1 (bash: in-f, after).
  • for i in 1 2; do f || echo caught; done | cat; echo after prints only after (bash: in-f, in-f, after).

This isn't a regression, but the PR closes #259. Would you rather mirror the counter in that loop here, or change "Fixes #259" to a partial reference so the issue stays open?

Reproduction details

Head 8aac37a, base dbb6189, bash 5.2.15, same setup as the other comment. Each script is prefixed with set -e; f() { false; echo in-f; };. Base and head give identical results on every row.

Script bash base and head
x=$(f || echo caught); echo "x=$x" x=in-f, 0 no output, 1
{ f || echo c; } > out.txt; cat out.txt; echo after in-f, after, 0 no output, 1
{ f && echo ok; } 2>/dev/null; echo after in-f, ok, after, 0 no output, 1
(f || echo c) | cat; echo after in-f, after, 0 after, 0
for i in 1 2; do f || echo c; done | cat; echo after in-f, in-f, after, 0 after, 0
if true; then f || echo c; fi | cat; echo after in-f, after, 0 after, 0

A scratch patch that mirrors the counter made all six rows match bash, and cargo test --workspace --all-targets still passed (2733):

// in run_capturing_status, around `let (exit, out) = match item { … };`
let ignored = u32::from(matches!(connector, Some(Connector::And) | Some(Connector::Or)));
proc.errexit_ignored += ignored;
let (exit, out) = match item { /* … */ };
proc.errexit_ignored -= ignored;

Two things to know if you take it:

  • The match has two early returns (src/exec.rs:2201 and :2232). Each needs proc.errexit_ignored -= ignored; before it, or a timeout there leaves errexit ignored for the next call on the same Shell.
  • It fixes f || handler in these contexts but not errexit there in general: set -e; { false; echo x; } > f.txt already keeps going on base, because this path never applies errexit to a compound.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mirrored the counter in the capturing loop in c63d8c8, including the decrement before both early returns (deadline and limits). Added differential case set_e_ignored_in_captured_body with your six rows; it failed on 8aac37a and matches bash now. Kept "Fixes #259". I left errexit on captured compounds in general ({ false; echo x; } > f.txt) alone, since it is the same on base and a separate bug.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c63d8c8. All six rows match bash, and a timeout inside a captured &&/|| list no longer leaves errexit ignored for the next call in the same MCP session (it did with a build missing the two early-return decrements).

@ferdingler

ferdingler commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Addressed the review in c63d8c8 (tests first in 83257f9). Non-blocking notes: 1) updated the stale counter comments in os.rs and shell.rs; 2) added set_e_break_out_of_tested_body; 3) added set_e_ignored_in_sourced_body for ./source; 4) I left the $(set -e; g) edge inside a tested function for a follow-up rather than grow this PR; 5) left the base-only bugs for separate issues. Full suite passes locally.

@strandly-the-agent Please review this PR

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. Both findings from my last review are fixed at c63d8c8, and I couldn't break either fix.

Previous finding Status
🔴 Child sh left of &&/|| ignored its own set -e Fixed
🟡 #259 still reproduced when the list's output was captured Fixed, including the two early returns

Notes 1 to 3 are done. Deferring 4 ($(set -e; g) inside a tested function) and 5 (the bugs that are also on base) is fine by me; both still behave as described.

CI: the Rust macOS and Windows jobs were still running when I posted this; every finished job passed.

What I verified

Head c63d8c8, previous head 8aac37a, base dbb6189, debug builds, bash 5.2.15 as the reference.

  • cargo test --workspace --all-targets: 2733 passed, 0 failed.
  • The four new .expected files match what bash prints. child_sh_in_tested_context and ignored_in_captured_body fail on 8aac37a and pass now. break_out_of_tested_body and ignored_in_sourced_body pass on both.
  • 54 targeted scripts compared across bash, base and head, 32 of them written to attack the two fixes. 47 match bash. The other 7 are the $(set -e; g) edge, four bugs that are also on base, and two shapes that hit the captured-compound bug below.
  • Re-ran 176 of the earlier adversarial scripts against this head: no crashes, and the only two that matched bash on base but not here are both the $(set -e; g) edge.
  • Counter leak: in one MCP session with set -e, I timed out five captured or tested shapes ({ { sleep 3; } | cat && echo x; } > out.txt, x=$(sleep 3 && echo x), a piped for loop, a redirected group calling a function, sh -c 'sleep 3' || …). After each one, false; echo LEAK exited 1 with no output. A build without the early-return decrements prints LEAK on the first shape.
  • Not run: Python and Node bindings, release builds, cargo fmt/clippy (not installed in my sandbox).

One behaviour change to be aware of, from the bug you chose to leave: set -e; { f || true; false; echo no; } > out.txt used to exit 1 like bash, but only because f killed the script. Now f || true is handled correctly and the group carries on past false, since the capturing path never applies errexit to a compound. Same root cause as set -e; { false; echo x; } > f.txt.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] set -e still fires inside a function/group/eval body called from a tested context (f || handler)

2 participants