Skip to content

feat(parser): support [[ ]] conditional expressions - #325

Merged
ferdingler merged 5 commits into
strands-agents:mainfrom
abhisheksp:feature/parser/double-bracket
Nov 20, 2026
Merged

ferdingler merged 5 commits into
strands-agents:mainfrom
abhisheksp:feature/parser/double-bracket

Conversation

@abhisheksp

Copy link
Copy Markdown
Contributor

Description

Context. Agents run scripts that test with [[ ]]. Claude Code 2.1.316 and later writes grep, find, and rg wrapper functions into the shell it uses, and each one branches on [[ -x <path> ]], [[ -n ${ZSH_VERSION:-} ]], and [[ "$OSTYPE" == "msys" ]].

Before. [[ was not recognized, so each of those tests printed [[: command not found. Every wrapper then fell through to a branch that the shell cannot run, so grep, find, and rg failed in the agent's shell.

After. [[ ... ]] is a compound command, Item::Conditional, that holds its operands unexpanded. The evaluation expands an operand only when it reaches it, without splitting or globbing, so && and || skip the operands they do not need, as bash does. The new command supports:

  • !, &&, ||, and parentheses;
  • the test operators, plus -v;
  • arithmetic operands for -eq and the other numeric comparisons;
  • ==, =, and !=, with a case pattern on the right.

=~ is refused with status 2. No alias expands inside [[ ]]. A file test on an empty path is now false, for test and [ too, as in bash.

Verification.

  • New differential cases double_bracket and double_bracket_alias, recorded from bash, cover:
    • the operators;
    • no splitting or globbing;
    • empty operands;
    • short-circuit operands whose substitutions must not run;
    • "$@";
    • a case arm;
    • a pipe, a redirect, and a function body;
    • a line break after &&;
    • no alias expansion inside [[ ]].
      Both cases fail on main and pass with the change.
  • cargo test: every suite passes. a_here_doc_cut_short_by_the_deadline_writes_no_partial_body failed once under full-suite load (it has a 200 ms deadline) and passed on three reruns and on the next full run.
  • cargo fmt --check passes, and cargo clippy --all-targets shows 15 warnings, the same as main.
  • End to end in an embedder that runs the shell under a policy, with Claude Code 2.1.316 and 2.1.328 and this change together with fix(exec): run command NAME without the shell function NAME #324:
    • echo hi | grep -c hi prints 1;
    • grep -rn and find . -name find the file;
    • rg without a binary exits 127 with command not found, and nothing recurses.

Related Issues

Part of #323. Works together with #324.

Documentation PR

None.

Type of Change

New feature

Testing

  • I ran the relevant test suites for the bindings I touched (cargo test; no binding changed)
  • 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
  • My changes generate no new warnings

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

Scripts that agents run, such as the grep and find wrappers that Claude
Code writes, test with [[ ]], which the shell reported as command not
found.

[[ ... ]] is now a compound command, Item::Conditional, which holds its
operands unexpanded. The evaluation expands an operand only when it
reaches it, without splitting or globbing, so && and || skip the
operands they do not need. It supports !, &&, ||, parentheses, the test
operators, -v, arithmetic operands for -eq and its kin, and == and !=
with a case pattern on the right. =~ is refused with status 2. No alias
expands inside [[ ]]. A file test on an empty path is false, in test and
[ too.

The differential cases double_bracket and double_bracket_alias pin it
against bash; both fail on main.
@ferdingler

Copy link
Copy Markdown
Collaborator

@strandly-the-agent 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.

Changes requested. [[ ]] evaluates well-formed input like bash (11,073 fuzzed expressions, no mismatch in status or short-circuit order), but one case gives a silent wrong answer. @ferdingler

  • 🔴 A quoted right-hand side of ==/!= is matched as a glob, so [[ "$a" == "$b" ]] is wrong whenever $b holds *, ? or [. Inline, with a tested fix.
  • 🟡 A short-circuited =~ swallows the rest of the expression and reports nothing.
  • 🟡 A line break after [[, before ]], or before &&/|| is a parse error that stops the script.
  • 🟡 Ten mutants of the new code survive the two differential cases, including one that removes && short-circuiting. Inline, with lines to add.
  • Merge order: land #324 first. On its own this PR turns the Claude Code grep wrapper's exit 127 into unbounded recursion: a stack-overflow abort on a debug build, maximum recursion depth exceeded on release.
What I verified, questions, reading order, appendix

Verified at head 969a13e against base 4b0bdbc (the merge-base) and bash 5.2.15, debug builds on aarch64 Linux:

  • cargo test --workspace --all-targets: 2,662 passed, 0 failed, 0 ignored, exit 0. cargo fmt --check is clean. cargo clippy --workspace --all-targets prints the same warning summary as base.
  • Both new cases fail on base with [[: command not found.
  • A three-way harness (bash, base, PR) over 3,938 scripts. Of the 1,800 that use [[, 1,323 match bash; most of the rest trace to gaps that base also has.
  • 11,073 random valid expressions match bash on status and on the order of operand side effects, apart from 8 -s <dir> cases (the VFS reports size 0, same as [ on base). 15,000 malformed inputs caused no hang or crash.
  • [ and test after the eval_unary change: 1,612 cases, 116 fixed, 2 regressions (see appendix).
  • These hold: no splitting or globbing of operands; </> create no file; -v on globals and locals; use in if/while/until, after !, in pipes, subshells, functions, eval, under set -e and set -u; 65,536-term chains and 16 MB operands stay linear.
  • Not tested: the Python, Node.js and WASM bindings, a real tty for -t, and the embedder run described in the PR.

Questions (non-blocking)

  1. Is =~ planned as a follow-up? regex is already a dependency, and =~ is common in agent scripts. Today a guard such as if [[ $x =~ re ]]; then exit 1; fi prints the refusal and carries on.
  2. The published Shell language and builtins page says "No [[ ]]" in the test, [ row, and the PR lists no documentation PR. That row needs updating, with the remaining gaps (=~, extglob, -o, -N, -R).
  3. Item::Conditional and pub enum CondTerm extend the public parser AST, which has no #[non_exhaustive]. #205 added a variant the same way and the crate is at 0.0.0, so I did not treat this as an API change. Say so if the AST is meant to be stable.
  4. Should the empty-path rule live in the kernel under #322 instead of test.rs:161-164? The guard covers unary operators only: [[ "" -ef "" ]] is still true.

Reading order: parser.rs:284-346 (parse_conditional), exec.rs:2764-2939 (the evaluator), exec.rs:2941-2980 (the skip path, which must mirror the evaluator), test.rs:161-164, then the cases.

Appendix, non-blocking (9)

  • [[ a =~ b ]] 2>/dev/null still prints the refusal; a 2> on the conditional or on an enclosing group does not capture its own diagnostic.
  • e=; [ ! -a "$e" ] now returns 0 (bash 1, base 1), from the guard at test.rs:161-164.
  • test -d "" with a literal "" still returns 0, because the empty argument is dropped before test runs (#299). The fix reaches "$e" with e= and [[ -d "" ]].
  • Valid bash that is refused: [[ $n == +([0-9]) ]] (status 2), [[ $v == @(a|b) ]] (parse error), -o, -N, -R, and [[ -v 1 ]] (false).
  • f=a; [[ -N $f ]] prints [[: unexpected `` with an empty name: cond_term_text (`exec.rs:2786`) is blank for any word that has an expansion or quotes.
  • The new parse errors start with syntax error:, which is_definite_error (parser.rs:173) does not recognise, so the rest of the script is read before the error is reported, without a line number.
  • The alias skip (parser.rs:232) misses a [[ that is the first command of a case arm, and echo then [[ a; foo no longer expands the alias foo.
  • set -x does not trace [[. [[ a ]] | [[ b ]] and { echo a; } | [[ -n a ]] report [[: command not found.
  • Pre-existing: case matches quoted patterns as globs too, filed #327. [ a = ] panics, already #321.

Comment thread src/exec.rs Resolved
Comment thread src/parser.rs Resolved
Comment thread src/parser.rs Resolved
- A quoted part of the right side of ==, = or != now matches
  literally. Each quoted part is escaped before glob matching, so a
  mixed word such as *"$y"* also matches as bash does.
- =~ is refused before evaluation starts, so a short-circuit can no
  longer skip the refusal and the terms after it.
- A line break inside [[ ]] is now allowed anywhere, as in bash. A
  literal ; inside [[ ]] is now a syntax error, as in bash. The
  errors start with "unexpected", so they are reported as definite
  parse errors.
- [ a -a b ] and [ a -o b ] with three arguments use the POSIX
  binary rule, so [ ! -a "$e" ] is false again for an empty $e.
- -ef, -nt and -ot treat an empty path as a missing file.

The double_bracket differential case has new lines for each fix and
for the short-circuit, grouping and precedence paths, recorded with
bash 5.2.15. Rust tests cover the =~ refusal, an unclosed group, a
literal ;, two operands, an unclosed [[, the empty-path guard, and a
command run through the Claude Code wrapper functions.
@abhisheksp

abhisheksp commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@strandly-the-agent Please re-review. The fixes are in 511e94d, and e0cbcfe merges main (with #324) into this branch.

Findings

  • 🔴 Quoted right side: fixed. A mixed word such as *"$y"* is fixed too.
  • 🟡 =~ short-circuit: it is now refused before evaluation.
  • 🟡 Line breaks: they are now allowed everywhere inside [[ ]], and a literal ; is rejected, as in bash.
  • 🟡 Mutants: all 10 of yours and 4 new ones now fail. New lines are re-recorded with bash 5.2.15, and Rust tests cover what a differential case cannot.
  • Merge order: fix(exec): run command NAME without the shell function NAME #324 is merged and is now in this branch. The wrapper test runs grep and find through the sourced functions.

Appendix items fixed in the same commit

  • e=; [ ! -a "$e" ] returns 1 again. Three-argument test with -a/-o now uses the POSIX binary rule.
  • [[ "" -ef "" ]] is false. -nt and -ot treat an empty path as a missing file.
  • The new parse errors start with unexpected, so is_definite_error recognises them. [[ ]] and a literal ; are definite, and an unclosed [[ is still incomplete input.

Not changed, as follow-ups

  • An unquoted \* on the right side is still a pattern. The tokenizer drops the escape, which is the same root cause as [BUG] case matches a quoted pattern as a glob (case abc in "a*") matches) #327.
  • =~, extglob patterns, -o, -N, -R, and [[ -v 1 ]].
  • 2> does not capture the conditional's own diagnostic. set -x does not trace [[. [[ as a later stage of a pipeline is not supported.
  • The diagnostic text from cond_term_text is blank for an expanded operand.
  • The alias-skip gaps (a [[ at the start of a case arm, and echo then [[ a; foo).

Questions These are open for the author to answer:

  1. Is =~ a follow-up PR?
  2. The docs row that says "No [[ ]]": should it be updated in a separate docs PR?
  3. Is the parser AST meant to be stable?
  4. Should the empty-path rule move into the kernel under [BUG] An empty path operand is treated as the current directory (mv "$empty" ../x renames the cwd) #322? Note: the kernel's stat of "" resolves to the working directory today, which is why the guard sits in test.rs.

Verified

  • cargo test --workspace --all-targets passes on Amazon Linux 2023 with bash 5.2.15: 2,689 passed, 0 failed.
  • cargo fmt --check and cargo doc with -D warnings are clean. The cargo clippy --workspace --all-targets warning summary is the same as on main.

@abhisheksp

Copy link
Copy Markdown
Contributor Author

@strandly-the-agent Please review this agent

@ferdingler

Copy link
Copy Markdown
Collaborator

@strandly-the-agent re-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.

Approve. All four findings from my last review are fixed at 511e94d, and #324 is in the branch. The fix commit brought in one small regression, which is worth taking before merge. @ferdingler

Previous findings:

  • 🔴 Quoted right side of ==/!=: fixed, including mixed words such as *"$y"*.
  • 🟡 Short-circuited =~: fixed. It is refused with status 2 before evaluation.
  • 🟡 Line breaks inside [[ ]]: fixed. A literal ; is now rejected.
  • 🟡 Test gaps: fixed. I re-ran my ten mutants: nine now fail, and the tenth no longer applies.
  • Merge order: resolved. The wrapper repro prints 1 and exits 0.

New in this round:

  • 🟡 -nt and -ot are true when both paths are empty, in [[, [ and test. [ and test return 1 on main. Inline, with a tested fix.
  • 🟡 Four of twelve mutants of the fix commit pass every test. Inline, with lines to add.
What I verified, open questions, appendix

Verified at head 511e94d against base 55d7816 (the merge-base) and bash 5.2.15, debug builds on aarch64 Linux:

  • cargo test --workspace --all-targets: 2,689 passed, 0 failed, 0 ignored, exit 0. cargo fmt --check is clean. cargo clippy --workspace --all-targets prints the same warning summary as base.
  • The four earlier repros and their controls now match bash. I re-checked the threads the author resolved.
  • The ten mutants that survived at 969a13e, re-run at this head against the lib, differential, shell_integration and claude_code_preamble tests:
    • Nine fail: the trailing-term check, the width of a skipped binary primary, the skipped ( group, && short-circuiting, the empty-expression check, != as a pattern, the missing-) check, -v on a set-but-empty variable, and the empty-path guard.
    • I rewrote two of those nine for the new code: the empty-expression check has a new message, and != now goes through escaped_glob_match.
    • The tenth (=~ returns false instead of an error) no longer applies, because the =~ arm in conditional_primary is gone. Its replacement, the refusal in execute_conditional switched off, fails too; it is one of the twelve below.
  • The 3,938-script harness from the first review, re-run with the previous head 969a13e as the comparison: 3,108 scripts match bash, 50 newly match, and 2 changed for the worse. Both are the intended refusal ([[ -z x && abc =~ ^a ]] now returns 2 with a message).
  • 358 new probes aimed at the fix:
    • Pattern escaping: 58 of 61 match bash, including the prefix idiom [[ "$p" == "$d"/* ]] and the contains idiom [[ "$l" == *"$n"* ]] with [, *, ? and \ in the quoted part.
    • A [[ that is not in command position, followed by a line break (echo [[, for i in [[ a, x=[[, a redirect target, a function argument, a here-doc body, a multi-line string): 24 of 26 match. The other two fail on base for other reasons.
    • A multi-line [[ in 29 contexts (if, elif, else, while, until, do, {, (, !, &&, ||, |, &, case arms, functions, $( ), backticks, eval): 27 match.
    • Three-argument test with -a/-o: no case changed for the worse.
  • 12 new mutants of the fix commit, run against the same four test targets: 8 fail, 4 pass.
  • Not tested: the Python, Node.js and WASM bindings, and a real tty for -t.

Still open for a maintainer (unchanged from the first review): whether =~ is a follow-up; the docs row that says "No [[ ]]"; whether the parser AST is stable API, since Item::Conditional and CondTerm extend it and the PR has no API-review label; and whether the empty-path rule belongs in the kernel under #322.

Appendix, non-blocking (4)

  • function f { [[ -n a ⏎ ]] && echo ok; } is a parse error. The tracker does not treat the { after function NAME as a command start. It needs the [[ on the same line as function f {.
  • x='=~'; [[ $x == =~ ]] and [[ -n =~ ]] are now refused, where bash treats =~ as a plain word. This follows from refusing before evaluation.
  • A quoted character inside an unquoted bracket expression is not literal ([[ '\' == [a"*"] ]] matches), and ${u:-"*"} on the right is still a pattern.
  • Pre-existing: a here-doc inside if, a loop, a group or a function takes the wrong lines as its body. I hit it while testing [[ before a here-doc and filed #333.

Comment thread src/builtins/test.rs Resolved
ferdingler and others added 2 commits November 19, 2026 20:11
An empty operand of -nt or -ot is a missing file. The guard stated
the other operand when one side was empty, and the kernel resolves
"" to the working directory, so two empty paths compared as true.
The guard now stats an operand only when it is not empty.

New double_bracket lines cover a line break after `then` and after
`&&`, a quoted bracket after a star, and -nt/-ot with empty paths.
They were recorded with bash 5.2.15.
@ferdingler
ferdingler merged commit ccbfb15 into strands-agents:main Nov 20, 2026
33 of 34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants