Conversation
The pattern `x=$(grep -c PATTERN file 2>/dev/null || echo "0")` has a
subtle duplication bug that shows up only when the pattern matches zero
lines:
- `grep -c` ALWAYS prints a count to stdout, including "0" for no matches.
- `grep -c` exits with status 1 when there are no matches (not 0).
- The `|| echo "0"` fallback fires on the non-zero exit and appends
ANOTHER "0" to the captured output.
- Result: `x` is a two-line string `"0\n0"`, which then blows up the
next arithmetic step with:
bash: 0
0: syntax error in expression (error token is "0")
This fires every Ralph loop iteration in `should_exit_gracefully()` and
`build_loop_context()` when `fix_plan.md` has no matching checkboxes
(e.g. a freshly generated plan, or a plan where all items use a different
indent level than the regex expects). Ralph continues past the error
(the arithmetic just evaluates to 0), so it's non-fatal — but the error
lines are alarming in `live.log` and indistinguishable from a real crash
for anyone tailing the log.
The same anti-pattern exists in several other places:
- `create_files.sh` (generator template — emits the bug into every
freshly-enabled Ralph install)
- `ralph_enable_ci.sh` (task import for beads / github / PRD paths)
- `lib/response_analyzer.sh` (question detection loop — masked by
downstream `tr -d` + `${var:-0}` sanitation, but still UB)
Fix: pipe through `head -1` to keep only the first line of output, then
validate with `[[ "$var" =~ ^[0-9]+$ ]]` and fall back to `0` if
anything non-numeric slipped through. This gives a guaranteed-integer
result regardless of whether grep matched, failed, or was missing the
input file.
Reproduction:
$ echo "" > /tmp/empty.md
$ x=$(grep -cE "foo" /tmp/empty.md 2>/dev/null || echo "0")
$ echo "$((x + 1))"
bash: line 1: 0
0+1: syntax error in expression (error token is "0")
After the fix:
$ x=$(grep -cE "foo" /tmp/empty.md 2>/dev/null | head -1)
$ [[ "$x" =~ ^[0-9]+$ ]] || x=0
$ echo "$((x + 1))"
1
|
Caution Review failedPull request was closed or merged during review No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
WalkthroughThe pull request fixes unreliable output counting in shell scripts across four files. Previously, grep counting logic used Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Closed without authorization. Please disregard.