[BUG] run_in_background Bash deletes the output of a command that exits before backgrounding completes
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
A Bash call with run_in_background: true whose command exits very quickly, before the tool finishes backgrounding it, intermittently loses its entire output. The command ran and printed its output, then the harness deleted it. The task's output file ends up holding only the completion marker ([exited with code N]), or it no longer exists.
The code path is identical in 2.1.280 and 2.1.285:
background(taskId, opts)backgrounds a command only while its status is"running". If the command has already completed, it returnsfalsewithout setting the background task id, and the caller does not check that return value.- The completion path runs
setImmediate(() => { if (!backgroundTaskId) taskOutput.deleteOutputFile() }). The id was never set, so the output file is deleted. - The completion marker is then written in one of two ways:
- through a fresh create, so the path holds only the marker; or
- into the file just before the unlink, so no path remains.
What Should Happen?
The command's output should be kept. When backgrounding loses the race with completion, either keep the output file for the background task, or return the output inline the way a foreground call does.
Error Messages/Logs
Content of tasks/<id>.output after the command in "Steps to Reproduce" finished:
[exited with code 1]
On other runs the file does not exist at all.
Error Messages/Logs
Steps to Reproduce
- Ask Claude to run this with the Bash tool and
run_in_background: true:
for i in 1 2 3 4; do echo LINE_$i; done; exit 1
- When the task-completion notification arrives, read the task output (BashOutput, or
tasks/<id>.output). - Repeat a few times. It is a race, so it happens intermittently.
- Observed (some runs): only
[exited with code 1], or no output file. - Expected:
LINE_1…LINE_4, then[exited with code 1]. - Workaround: starting the command with
sleep 1;avoids it, because the command is then still running when it gets backgrounded.
Claude Model
None
Is this a regression?
I don't know
Last Working Version
_No response_
Claude Code Version
2.1.280 (Claude Code). The same code path is present in 2.1.285.
Platform
Anthropic API
Operating System
Ubuntu/Debian Linux
Terminal/Shell
Terminal.app (macOS)
Additional Information
Related but distinct: #90616, where a background command killed by its timeout is reported as completed (exit code 0). Here the command completes normally, and its already-written output is deleted.