Skip to content

feat: parse common bash constructs (shopt, function keyword, etc) - #205

Merged
ferdingler merged 14 commits into
strands-agents:mainfrom
ferdingler:feat/parse-claude-code-preamble
Nov 11, 2026
Merged

ferdingler merged 14 commits into
strands-agents:mainfrom
ferdingler:feat/parse-claude-code-preamble

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A lot of common bash currently fails to parse here or expands to the wrong thing. This PR fixes all of these:

  • shopt with -s, -u, -q and -p. It records state, and -s only turns on expand_aliases, which Shell already does. Any other option is refused as not supported, so a script never thinks something like nullglob is on when it isn't. Unknown option names are refused, like bash.
  • function f { … } and function f () { … }.
  • x+=b, which used to set a variable called x+.
  • Quoted words inside ${name op word}, so ${1+"$@"} keeps each argument as its own field.
  • Subscripts on a plain variable, so ${x[0]} and ${x[@]} give $x.
  • A pipe into a compound command, like cmd | while read v or cmd | { …; }. The loop reads the left side's output as it comes, and return, break and exit stay inside the loop, like the subshell bash runs it in.
  • name=(…) parses, so a function containing one still gets defined. Running it is refused, because arrays aren't supported.

There's no public API change. The pipe-into-loop case gets rewritten into node types the parser already had, so code that matches on the parser's syntax tree keeps compiling. I checked it with semver-checks against main.

Two small bash fixes came along with it: a subshell now gets its caller's stdin, and a command writing into a pipe whose reader went away now stops quietly instead of printing an error.

One limit is left: a function that never ends, piped into a loop, still waits, because a function in a pipeline sends its output when it finishes. Main has the same limit for p | head, and I'll handle it separately.

Also, the CLI's -c path now runs on the heap, so a debug build doesn't overflow the Windows main-thread stack.

Out of scope: group redirects and $(eval …) capture are in a follow-up PR I have planned (#206). A ! before a compound command is still dropped, which is an existing gap.

Evidence from Box

We realized this because Claude Code's shell preamble uses all of these, so when it uses Shell it would always fail. So, we fixed all of these in Box already.

Related Issues

Documentation PR

Type of Change

New feature

Testing

Each construct has its own test, with the expected output checked against bash, and the real preamble runs end to end as a test. I also compared about 30 small pipe-into-loop scripts with bash on Linux. They match, except for the never-ending function above, arrays (refused on purpose), and an existing problem where a command inside a loop can eat the loop's input. To make sure the new streaming test means something, I ran it against the previous version of this PR, and it failed there. CI is green on Linux, macOS and Windows.

  • 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 ferdingler changed the title feat: parse and run the constructs in Claude Code's Bash preamble feat: parse common bash constructs (shopt, function keyword, +=, nested quoted expansions, pipe into compound) Nov 5, 2026
@ferdingler ferdingler changed the title feat: parse common bash constructs (shopt, function keyword, +=, nested quoted expansions, pipe into compound) feat: parse common bash constructs (shopt, function keyword, etc) Nov 5, 2026
@ferdingler
ferdingler marked this pull request as ready for review November 5, 2026 20:36
@ferdingler
ferdingler requested a review from a team as a code owner November 5, 2026 20:36
@ferdingler
ferdingler enabled auto-merge (squash) November 8, 2026 21:16
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent review

@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.

Request changes. The new constructs parse and CI is green, but two of them now give silently wrong results:

  1. 🔴 A quoted ${x:-}, ${x-} or ${x+…} that expands to empty now produces no argument instead of one empty argument (bash and main give one). This breaks the common set -u guard: [ -n "${DEBUG:-}" ] is now always true.
  2. 🔴 return, break and continue inside cmd | while … escape the pipeline's subshell, so the code after the loop is silently skipped.

There are 3 🟡 items inline and two questions below. One question is about API review: the PR makes public parser enums #[non_exhaustive] but has no needs-api-review label. The other is about the verbatim Claude Code fixture.

@ferdingler, both 🔴 fixes are one-liners (suggestions inline). I checked both against bash.

✅ What I verified
  • Head 71c6b7e: cargo test --workspace --all-targets passed 2,071 tests, 0 failed.
  • Ran about 50 small repros on base, the PR and /bin/bash.
  • Applied both suggested fixes and rebuilt. These now match bash:
    • f "${1:-}" gives argc=1.
    • set -- a "b c"; f "${1+"$@"}" gives argc=2.
    • g(){ echo x | while read l; do return 3; done; echo after; }; g prints after, rc=0.
    • break 2 in a piped loop prints i=1 and i=2.
  • I didn't run the full test suite with the fixes applied.
Questions
  • API review. pub mod parser (src/lib.rs:154) exports WordPart, Item, Redirect and Connector. They now get #[non_exhaustive] and new variants. That's reasonable before 1.0, with no Rust consumers published, but it still needs the needs-api-review label, and probably a feat! title.
  • Licensing. tests/fixtures/claude-code-snapshot-script.sh is described as Claude Code 2.1.285's script copied verbatim. Is a copy OK in an Apache-2.0 repo, or should it be a minimal, independently written equivalent covering the same constructs?
  • Buffering. The left side of cmd | while runs to completion before the loop starts. The PR documents this, but it means tail -f log | while … never enters the loop. Is that acceptable, or should it stream like run_pipeline does?
Reading order

src/exec.rs:468 → src/exec.rs:2086-2141 → src/parser.rs:1414-1485 → src/builtins/shopt.rs

Appendix — non-blocking (10)

Pre-existing (same on main). These limit how useful cmd | while read is in practice, so they may be worth issues:

  • Loop bodies lose stdin. Any isolated command or heredoc in a loop body fed from stdin fails with read: bad fd 0. For example, while read v; do ls /; done < f processes one line and stops. printf 'a\nb\n' \| while read l; do cat <<E … behaves the same.
  • read mishandles a partial last line. On a line with no trailing newline, read returns 0, and it doesn't clear the variable at EOF. So while read l \|\| [ -n "$l" ]; do … loops forever (10s timeout on both base and the PR).
  • Smaller pre-existing gaps:
    • (cmd) < f gets no stdin.
    • "$unset" yields 0 args instead of 1.
    • export P+=b and local L+=b still don't append.

⚪ nits

  • shopt differs from bash in a few ways: shopt -sq extglob is rejected (bash accepts bundled flags); shopt -s a nosuch turns on nothing; and the listing format and default-on options differ.
  • ! a \| while …; done \| cat drops the negation: rc 0, where bash gives 1. The cause is the false at parser.rs:1451.
  • The array error doesn't name the variable, and a top-level arr=(…) aborts the whole script with exit 2.
  • In echo ${x[0}; echo "]", the subscript lookahead runs past } and swallows the next command. That input is malformed and bash rejects it anyway.
  • The head runs in the parent, so v=changed \| while … leaves v=changed.
  • README.md:118,252 still say "25 builtins".

Comment thread src/exec.rs Resolved
Comment thread src/exec.rs Resolved
Comment thread src/parser.rs Resolved
Comment thread src/parser.rs Resolved
Comment thread src/builtins/shopt.rs Resolved
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent addressed all your comments, please confirm

@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 🔴 are fixed and match bash. I'm lifting my block. Two 🟡 items are left; I'd fix them before merge:

  • ( … ) plus a redirect, piped into: fixed for the bare case only. echo a | ( read v; echo "v=$v" ) 2>/dev/null still prints v=, where bash prints v=a. There's a one-line suggestion inline.
  • shopt -s allowlist: not addressed. That thread was resolved without a reply or a change. shopt -s nullglob still reports success, and the loop still runs on the literal /nope*. Was leaving it as is deliberate?

The questions from last time are still open: the needs-api-review label (none yet), the verbatim Claude Code fixture, and buffering. They're for maintainers to decide, so they don't block from my side.

✅ What I verified (head 3d9f404)
Previous finding Status
🔴 empty quoted ${x:-} / ${x-} / ${x+…} fixed. f "${1:-}" gives argc=1, and [ -n "${DEBUG:-}" ] under set -u is false. The new unquoted split (f ${u:-a b} gives 2) matches bash too.
🔴 return/break/continue escape cmd | while fixed. return 3 gives after 3/rc=0, break 2 and continue 2 give i=1 i=2, exit 5 stays in the loop, and the $(…) path behaves the same.
🟡 cmd | ( … ) loses stdin fixed for bare ( … ), | ( … ) | cat and $(…). Still broken when ( … ) has a redirect (inline).
🟡 redirects after done wrap the head fixed. 2>e3.txt catches <a>, < /dev/null gives nothing, and ! … | false gives 0.
🟡 shopt -s accepts everything still open (no change in 3d9f404).
  • I ran about 30 repros against base 310ab94, the PR and /bin/bash. All match except the two open items. Log: strands-agents/shell/pr/205/followup-repros.log.
  • With the inline suggestion applied, cargo test --workspace --all-targets passed 2,073, 0 failed. Diff: strands-agents/shell/pr/205/suggested-fix.diff.
Appendix: non-blocking
  • These are pre-existing, and base 310ab94 behaves the same: f ${u:-a\ b} gives 2 args (bash gives 1), and f "" gives 0 args (bash gives 1).

Comment thread src/parser.rs Resolved
A pipe into a compound now parses to a subshell that defines the compound
as a function and calls it as one stage of the pipeline. A name=(...) list
now parses to two adjacent literals. The enum variants and the
#[non_exhaustive] attributes go away, so the parser API is the same as on
main. The head of the pipe now runs at the same time as the compound, so a
function head feeds the loop.

A subshell now gets the stdin of its caller, a function stage writes its
captured stderr to its own stderr, and a builtin stage that writes to a
closed pipe stops without a diagnostic.
@ferdingler

Copy link
Copy Markdown
Collaborator Author

API review. pub mod parser exports WordPart, Item, Redirect and Connector. They now get #[non_exhaustive] and new variants.

The enum changes are gone. The pipe-into-loop case is now rewritten into existing node types, so the public API is unchanged, and semver-checks passes against main.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

Buffering. The left side of cmd | while runs to completion before the loop starts.

The loop now streams its input from a pipeline head. A function head still sends its output when it ends. That's an existing engine limit, the same as p | head on main, and I'll handle it separately.

@ferdingler
ferdingler disabled auto-merge November 11, 2026 01:16
@ferdingler
ferdingler merged commit 1a888fc into strands-agents:main Nov 11, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants