Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/commands/bash/bash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,5 +237,16 @@ cat /tmp/test.txt`,
expect(result.stdout).toBe("line2\n");
expect(result.exitCode).toBe(0);
});

it("should handle command substitution with grep and head in piped bash -c", async () => {
const env = new Bash();
// This test demonstrates a bug where grep with no matches followed by head
// incorrectly passes through the original stdin instead of empty output
const result = await env.exec(
'echo "test" | bash -c \'RESULT=$(cat | grep "nomatch" | head -1); echo "RESULT=[$RESULT]"\'',
);
expect(result.stdout).toBe("RESULT=[]\n");
expect(result.exitCode).toBe(0);
});
});
});
9 changes: 9 additions & 0 deletions src/interpreter/pipeline-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,21 @@ export async function executePipeline(
for (let i = 0; i < node.commands.length; i++) {
const command = node.commands[i];
const isLast = i === node.commands.length - 1;
const isFirst = i === 0;

// In a multi-command pipeline, each command runs in a subshell context
// where $_ starts empty (subshells don't inherit $_ from parent in same way)
if (isMultiCommandPipeline) {
// Clear $_ for each pipeline command - they each get fresh subshell context
ctx.state.lastArg = "";

// After the first command, clear groupStdin so subsequent commands
// only see stdin from the pipeline (even if empty), not the original groupStdin
// This prevents commands like head from incorrectly falling back to groupStdin
// when they receive empty output from a previous command (e.g., grep with no matches)
if (!isFirst) {
ctx.state.groupStdin = undefined;
}
}

// Determine if this command runs in a subshell context
Expand Down