Skip to content

fix(test): reject a non-integer operand of an integer operator - #348

Open
ferdingler wants to merge 9 commits into
strands-agents:mainfrom
ferdingler:fix-334-test-integer
Open

ferdingler wants to merge 9 commits into
strands-agents:mainfrom
ferdingler:fix-334-test-integer

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

[ and test read an empty or non-numeric operand of an integer comparison as 0, so [ "" -lt 3 ] was true and [ abc -eq 0 ] passed quietly. A script that loops on an unset counter or checks a value it didn't validate would take the wrong branch with no error. Bash reports the bad operand and returns status 2, so the condition isn't taken.

Now [ and test do the same: an operand that isn't a decimal integer gets an error and status 2. Like bash, blanks around the number and a leading sign are still accepted, and [[ ]] is unchanged because there these operands are arithmetic. This is in the same test code as #321 (a missing operand), so the two may conflict, but I kept this one to integer operands only.

Related Issues

Fixes #334

Documentation PR

N/A

Type of Change

Bug fix

Testing

I added differential cases for bad operands and for forms that should still work, plus a check on the status and the error message. On main the bad operands came back true or false with nothing on stderr, and blanks around a number were rejected. With the change everything matches bash and the full test suite passes.

  • 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

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

No blocking findings. This fixes #334 and matches bash 5.2.15 on every realistic integer-operand case I ran. Posted as a comment; approval is a maintainer's call.

  • 🟡 A number after a leading newline or CR is rejected where bash accepts it. One-line fix inline.
  • 🟡 Five mutations of the new code pass the new tests; four extra differential lines catch four of them. Inline, optional.
  • Heads-up, not caused by this PR: $UID, $SECONDS, $PPID and friends are empty in this shell, so [ "$UID" -eq 0 ] goes from silently comparing 0 to an error and status 2 once this merges. Filed #367.
✅ What I verified

Head 9ef3e56 against base dbb6189 (= main). Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C as the oracle.

  • Suite at head: cargo test --workspace --all-targets exits 0 with 2,735 passed, 0 failed, 0 ignored. cargo fmt --check exits 0. cargo clippy --workspace --all-targets exits 0 with 14 warnings, none in src/builtins/test.rs. CI is green.
  • New tests fail without the fix: with head's tests/ on base's source, --test differential fails exactly the two new cases and --test shell_integration test_int_ fails the two new tests. All pass on head.
  • .expected files: a fresh bash recording of both new cases is byte-identical to the committed files.
  • Differential run: 231,006 scripts through bash, base and head, comparing status, stdout and whether stderr is empty.
    • 83,146 cases that differed from bash on base now match.
    • [[ ]]: 30,252 cases, byte-identical between base and head. exec.rs:2961-2970 passes both operands through eval_arith(...).to_string(), so the new trim in num() is a no-op there.
    • Expressions without an integer operator: 48,108 cases, byte-identical to base.
    • 3,647 cases matched bash on base and differ on head: 3,411 leading whitespace (inline), 230 parenthesised unary test (appendix), 6 unset special variables (#367).
  • Contexts that match bash: if/while/until, &&/||, !, set -e, unset $1 in a function, 2>/dev/null, -a/-o on either side, ( ).
  • Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms.
Questions, reading order, appendix

Question (non-blocking)

  • The checklist leaves "I have reviewed and understand every line of code in this PR" unchecked. AGENTS.md asks that every box can be checked truthfully before opening.

Reading order

src/builtins/test.rs:115-129 (the operand check), :28-41 (the message and status 2), :263-270 (integer), then the two differential cases.

Appendix, non-blocking (5)

  • ⚪ v=-lt; [ \( -n "$v" \) ] returns 2 with [: -n: integer expression expected; bash says true. -n -lt ) was already read as a binary comparison at test.rs:115-122, and the new check now rejects -n. It needs a lone parenthesised unary test on a string that is itself an integer operator.
  • ⚪ The name in the message comes from a trailing ], not the command: test abc -eq 0 ] reports [: where bash reports test:. Status is 2 in both.
  • ⚪ Still silent with status 1, same as base, where bash returns 2: [ "!" -eq 3 ], [ "(" -lt 3 ], test 3 -eq ], [ ! ! abc -eq 0 ].
  • This conflicts with #347 in builtin_test (both add let bracket), so the second to merge needs a rebase.
  • Pre-existing, same on base and head, filed: #367 (empty $UID, $SECONDS, …), #368 ($(( )) reads a blank-padded variable as 0), #369 (cmd &>file), #370 (stderr inside $( ) is dropped), #371 (a redirect on if/while/until skips the condition).

Comment thread src/builtins/test.rs Resolved
@ferdingler

Copy link
Copy Markdown
Collaborator Author

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

Both findings from the first review are fixed at 581183f; nothing new. Still a comment, not an approval.

  • ✅ Leading newline or CR before a number: fixed in 581183f. The repros match bash 5.2.15, and trailing \r and \n are still rejected as in bash.
  • ✅ Untested paths: fixed in a522f74. All five mutants that passed the old tests now fail.
✅ What I verified

Head 581183f against the previously reviewed 9ef3e56 and base dbb6189. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.

  • Suite at head: cargo test --workspace --all-targets exits 0 with 2,736 passed, 0 failed, 0 ignored (one more than before: the new integration test). cargo fmt --check exits 0. cargo clippy --workspace --all-targets exits 0 with no warning in src/builtins/test.rs. CI is green on all platforms.
  • Sweep: 1,172 scripts through bash, base, 9ef3e56 and 581183f: every ASCII byte 1 to 127 before the number, after it, between sign and digits, between digits and alone; six multi-byte spaces; all six operators with LF, CR, VT, FF and CRLF on either operand.
    • 581183f differs from bash on 2: a lone ! or ( as the left operand ([ "!" -eq 0 ]), unchanged and already listed in the first review's appendix.
    • 9ef3e56 differed on 122. The 120 lines that changed are exactly the ones that were wrong.
  • [[ ]]: a leading or trailing newline in an operand gives the same result on base, both heads and bash.
  • .expected files: a fresh bash recording of both cases is byte-identical to the committed files. 581183f matches both. 9ef3e56 fails the valid case on exactly leading-newline and leading-cr, so the test-first commit does fail before the fix. Base fails both cases.
  • Mutation re-run on a copy of 581183f (unmutated control passes both suites):
Mutant Result
tabs not trimmed fails test_integer_operand_valid
error right of -o dropped fails test_integer_operand_invalid
error inside ( ) dropped fails test_integer_operand_invalid
blanks-only operand accepted as 0 fails test_integer_operand_invalid
message prints the trimmed operand fails test_int_error_names_the_operand_untrimmed
leading trim back to space and tab fails test_integer_operand_valid
leading LF not trimmed fails test_integer_operand_valid
leading CR not trimmed fails test_integer_operand_valid
trailing LF, VT, FF, CR also trimmed fails test_integer_operand_invalid
leading VT and FF not trimmed passes both suites
  • Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms locally.
Appendix, non-blocking (1)
  • ⚪ A leading vertical tab or form feed isn't pinned by a test (last row above). Head is correct for both; I wouldn't hold the PR for it.

The other appendix items from the first review (parenthesised unary test, message name, ! and ( operands, the #347 conflict, the unchecked checklist box) are unchanged.

akujane
akujane previously approved these changes Nov 26, 2026

@kevin-orellana kevin-orellana left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

A valid nonempty-string check now reports an integer error when the string happens to be -eq. Could we evaluate the expression inside the parentheses before treating -eq as a comparison operator?

With v=-eq, [ \( -n "$v" \) ] returns 0 in Bash and on main. This branch exits 2 with -n: integer expression expected.

With v=-eq, [ \( -n "$v" \) ] is true in bash and on main but exits 2 on this branch. Recorded from bash 5.2.15.
Up to four arguments are read by count, as bash does, so a parenthesized -n or -z takes -eq as its operand and ( -eq ) is a comparison. Longer expressions still go to the parser.
@ferdingler

Copy link
Copy Markdown
Collaborator Author

With v=-eq, [ \( -n "$v" \) ] returns 0 in Bash and on main. This branch exits 2 with -n: integer expression expected.

@kevin-orellana thanks, good catch. Fixed in 886a4b2. test now applies the POSIX argument-count rules first, as bash does, for up to four arguments. So ( -n -eq ) evaluates the inner -n -eq as a two-argument test, and a middle -eq is only a comparison when the whole three-argument test is x -eq y. Longer expressions still go through the parser.

The test-first commit 51bfd03 adds test_paren_operator_as_operand, recorded from bash 5.2.15. It covers your repro plus ( -n -eq ), ( -n -lt ), ( -z -eq ), ! -n -eq, -n -eq, -eq, ( -eq ) and ( abc -eq 1 ). It failed on 581183f (your repro exited 2, and ( -eq ) was 0 where bash says 2) and passes now.

I also checked every 1 to 4 argument combination of ! ( ) -n -z -eq -lt -a -o = x "" 3 -f against bash and main. Nothing that matched bash on main differs now. I merged main into the branch as well.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

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

One new wrong answer in 886a4b2: ! now inverts a malformed expression to true. The fix for kevin-orellana's ( -n -eq ) repro works; this is a side effect of the new eval. Small fix inline, tested.

  • 🔴 v="a b"; [ ! $v ] is now true (status 0). main returns 1 and bash errors with status 2. So an if [ ! $v ] whose variable is unquoted and holds two or three words now takes the branch. Across 141,128 fuzz expressions, 6,690 go from false on main to true on this head where bash reports an error.
  • Otherwise the new arg-count rules hold up. No expression that matched bash on main (status and stderr) differs now, and 992 that the previous head got wrong now match. The new differential case is a byte-for-byte bash recording that fails on 581183f.
✅ What I verified

Head 886a4b2. I compared it with the previous review's head 581183f and with main 4f838f9, after the merge. Only 648a7aa..886a4b2 is new code here: the merge brings in main unchanged. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.

  • Suite at head: cargo test --workspace --all-targets exits 0 with 2,777 passed, 0 failed, 0 ignored. cargo fmt --check and cargo clippy --workspace --all-targets exit 0, with no clippy warning in src/builtins/test.rs. The only non-green check is the cancelled 2 Approvers for Bots job.
  • test_paren_operator_as_operand: a fresh bash recording is byte-identical to the committed .expected. 886a4b2 matches it. 581183f fails 6 lines and main fails 5.
  • Fuzz: I ran every 0 to 4 argument combination of ! ( ) -n -z -eq -lt -a -o = != x "" 3 " 3" abc -f -nt, plus 30,000 random 5 to 7 argument ones. That is 141,128 expressions, each as [ … ] and test … (282,256 runs). They were split into 4,000-line chunks because a single run hits the 30 s deadline.
main 581183f 886a4b2 with suggested fix
matches bash (status + stderr presence) 15,880 46,890 47,838 47,838
regressions vs main — — 0 0
false on main → true here, where bash errors — — 6,690 158
  • Suggested fix tested: it leaves the match count unchanged and adds no regression against main or 886a4b2. The differential and shell_integration suites pass with it (1 + 2,079), and cargo fmt --check passes. The remaining 158 cases are a dangling -a/-o such as [ ! x -a ]. The parser already accepts that form on main: [ x -a ] is a silent 1 there. That is #321 territory.
  • Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms.
Appendix, non-blocking (1)
  • ⚪ [ \( x -eq \) ] returns 1 here. Bash errors with x: unary operator expected and status 2. 581183f happened to error too, through the integer check, and main returned 0. This is the missing-operand case #347 covers, not something to fix in this PR.

Comment thread src/builtins/test.rs Outdated
}
[open, arg, close] if open == "(" && close == ")" => Ok(!arg.is_empty()),
[bang, rest @ ..] if bang == "!" && matches!(rest.len(), 2 | 3) => {
Ok(!eval(rest, os, proc).await?)

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.

! inverts a malformed sub-expression, so [ ! $v ] with a two-word $v is now true

When rest isn't one of the fixed 2- or 3-argument forms, eval(rest) falls through to the parser. The _ arm then returns Ok(false) because pos != args.len(), and this arm turns that into true. With v="a b", [ ! $v ] becomes [ ! a b ]. Bash prints a: unary operator expected and returns 2; main and 581183f return 1; this head returns 0. So if [ ! $v ]; then … runs the branch. set -- x y; [ ! "$@" ] and a three-word $v behave the same way. In the fuzz run, 6,690 expressions go from false on main to true here, all where bash errors.

Suggestion: have eval report "malformed" separately from "false" so that ! can't flip it. For example, return Result<Option<bool>, String>, with None from the _ arm when pos != args.len(). The ! arm then becomes Ok(eval(rest, os, proc).await?.map(|r| !r)), and builtin_test treats anything other than Some(true) as status 1, as main does. That keeps status 1 for now; #347 could later turn it into 2.

Reproduction details

Head 886a4b2, previous head 581183f, main 4f838f9, bash 5.2.15 with LC_ALL=C. Linux aarch64, debug builds, each script run with -c.

Script bash main 581183f 886a4b2 with fix
v="a b"; if [ ! $v ]; then echo empty; else echo nonempty; fi error, nonempty nonempty nonempty empty nonempty
v="a b c"; [ ! $v ]; echo rc=$? error, rc=2 rc=1 rc=1 rc=0 rc=1
set -- x y; [ ! "$@" ] && echo taken; echo rc=$? error, rc=2 rc=1 rc=1 taken, rc=0 rc=1
v=-eq; [ \( -n "$v" \) ]; echo rc=$? (control) rc=0 rc=0 error, rc=2 rc=0 rc=0
[ ! \( x \) ]; echo rc=$? (control) rc=1 rc=1 rc=1

The fix I tested, applied to 886a4b2:

-            Ok(result) => result,
+            Ok(result) => result == Some(true),
...
-) -> Pin<Box<dyn Future<Output = Eval> + 'a>> {
+) -> Pin<Box<dyn Future<Output = Result<Option<bool>, String>> + 'a>> {
     Box::pin(async move {
-        match args {
+        let result = match args {
...
-                Ok(!eval(rest, os, proc).await?)
+                return Ok(eval(rest, os, proc).await?.map(|r| !r));
...
-                eval(rest, os, proc).await
+                return eval(rest, os, proc).await;
...
-                Ok(result && pos == args.len())
+                return Ok((pos == args.len()).then_some(result));
             }
-        }
+        };
+        result.map(Some)

With it, the 282,256-run fuzz still matches bash on 47,838, the same as 886a4b2, with 0 regressions against main or 886a4b2. --test differential passes (including test_paren_operator_as_operand), --test shell_integration passes 2,079, and cargo fmt --check passes. A regression line such as v="a b"; [ ! $v ]; echo "not-two-words: $?" would pin it. Bash records 2 for that line, so it may belong in a known-difference case until #347 lands.

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.

Agreed, thanks. Applied in 8eeef48: eval returns Option<bool>, ! maps over it, and builtin_test treats anything other than Some(true) as status 1.

I also closed the remaining 158. Any form of three or fewer arguments that the POSIX rules don't cover now returns None without reaching the parser. Bash reports all of those as syntax errors, so [ ! x -a ] and [ ! ! \( ! ] stay false.

The test-first commit d410f83 adds [ ! $v ] with two and three words, [ ! "$@" ], [ \( a b \) ], [ ! x -a ] and [ ! ! \( ! ] to test_paren_operator_as_operand. Each is an if, so its output matches bash. Five of those lines fail on 886a4b2, and all pass now.

I swept every 0 to 4 argument combination of ! ( ) -n -z -eq -lt -a -o = x "" 3 -f against bash and main. No expression goes from false on main to true here. The only results that differ from main without matching bash are 159 bash syntax errors that main called true and this branch calls false (status 1), for example [ \( -n ].

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.

Verified at 8eeef48: [ ! $v ] with two or three words, [ ! "$@" ] and [ ! x -a ] now return 1 like main, and the five new lines in test_paren_operator_as_operand fail on 886a4b2 and pass here. Across 282,256 fuzz runs, 0 cases that matched bash on main differ now, and the false→true flips dropped from 6,690 to 8, all pre-existing parser leniency (see the review).

With v="a b", [ ! $v ] errors in bash and is false on main, but is true on 886a4b2. So are [ ! x -a ] and [ ! ! \( ! ].
eval reports a test it can't read whole as None, and ! leaves None as is, so the test is false as on main. Forms of three or fewer arguments outside POSIX's rules are malformed, as in bash, instead of going to the lenient parser.
@ferdingler

Copy link
Copy Markdown
Collaborator Author

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

The ! finding is fixed at 8eeef48; nothing new. Still a comment, not an approval.

  • ✅ ! no longer turns a malformed test true: [ ! $v ] with a two- or three-word $v, [ ! "$@" ], [ ! x -a ]. The new _ if args.len() <= 3 => None arm also closes the dangling -a/-o cases my suggestion left open.
  • The red Rust (windows-latest) check is compound_pipe_into_function_redirected_from_cli overflowing the stack. That is the known flaky failure in #406, in a pipe test that doesn't go through test, and 886a4b2 passed the same job. A re-run should clear it.
✅ What I verified

Head 8eeef48 against 886a4b2 and main 4f838f9. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.

  • Suite: cargo test --workspace --all-targets exits 0 with 2,777 passed, 0 failed, 0 ignored. cargo fmt --check exits 0, and clippy reports nothing in src/builtins/test.rs.
  • test_paren_operator_as_operand: a fresh bash recording is byte-identical to the committed .expected. 8eeef48 matches it. 886a4b2 fails exactly the five new not-* lines.
  • Fuzz: the same 282,256 runs as last time (141,128 expressions × [ ]/test).
main 886a4b2 8eeef48
matches bash (status + stderr presence) 15,880 47,838 47,842
regressions vs main — 0 0
false on main → true here, where bash errors — 6,690 8
true on main and bash, not here — — 0
  • Not run: Python and Node bindings, WASM, the MCP server, release builds, Windows locally.
Appendix, non-blocking (1)
  • ⚪ The 8 remaining false→true cases are an unclosed ( or a dangling -o after a blank-padded integer, e.g. [ \( 3 -eq " 3" ] and [ " 3" -eq 3 -o ]. Bash reports a syntax error. The parser already accepts both forms on main, where [ \( 3 -eq 3 ] is also true. They only flip here because " 3" now reads as 3. That is #321 territory, not this PR.

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] [ / test integer operators read an empty or non-numeric operand as 0 ([ "" -lt 3 ] is true)

4 participants