Skip to content

Bun.spawn, stdio and exit codes

Relay’s deliver step called tar through one shell string: `tar -xf ${archive} -C ${dir}`. It worked until a source was registered under the name x; rm -rf ~. The shell parsed the string, found a second command, and ran it. A container CLI like tsbox is a program that starts other programs all day, so this lesson is about doing that without a shell in the middle, and without losing the exit code, the output or the child.

tsbox is a small container CLI in the style of podman: no daemon, no root. Every lesson in this module follows functional core, imperative shell: pure functions compute argv, plans and messages, and a thin shell calls Bun.spawn. That is also why the tests run on macOS even though containers need Linux.

Bun.spawn starts a program and returns at once with a handle. Bun.spawnSync blocks until the program ends and returns everything in one object:

const child = Bun.spawn(["echo", "hello"], { stdout: "pipe" })
const text = await new Response(child.stdout).text()
const code = await child.exited // a Promise<number>
console.log(text, code) // "hello\n" 0
const done = Bun.spawnSync(["echo", "hello"])
console.log(done.exitCode, done.success, done.stdout.toString())

Use spawnSync in a start-up script that has nothing else to do. Use spawn in a server: spawnSync freezes the event loop (lesson 1 of concurrency), so every other request waits for the child.

The first argument is the argv: the program, then one array element per argument. No shell reads it, so spaces, quotes, ; and $ are just characters:

declare const source: string // "x; rm -rf ~"
// Wrong: `sh -c` parses the string, so the `;` starts a second command.
Bun.spawn(["sh", "-c", `echo registered ${source}`])
// Right: `echo` receives one argument, whatever it contains.
Bun.spawn(["echo", "registered", source])

If you really need a shell feature such as a pipe, write the script as a constant and pass the data as positional arguments (sh -c 'wc -l < "$1"' sh "$file"). Lesson 4 uses exactly that. A rule that holds everywhere: data never becomes part of code.

Each of stdin, stdout and stderr is configured separately:

  • "pipe": tsbox reads or writes it through the handle. stdout and stderr become a ReadableStream, stdin a sink.
  • "inherit": the child shares tsbox’s own terminal. Use it for tsbox run -it, where a human types.
  • "ignore": discard it. Use it for output nobody reads, so a pipe cannot fill up.
const child = Bun.spawn(["cat"], { stdin: "pipe", stdout: "pipe" })
child.stdin.write("payload")
void child.stdin.end() // without this, `cat` waits for more input forever
console.log(await new Response(child.stdout).text())

A child that waits for end-of-input is the most common hang. Closing stdin is how you say “that is all”.

child.exited resolves to a number. A normal exit gives the program’s own code: 0 is success, anything else is up to the program. A child killed by a signal also gives a number, 128 + signal number, as a shell reports it. The handle tells the two apart:

const child = Bun.spawn(["sleep", "10"])
child.kill("SIGTERM") // ask politely; "SIGKILL" cannot be ignored
const code = await child.exited
console.log(code, child.signalCode) // 143 "SIGTERM"

The values in that comment are what Bun 1.3.10 printed in our test on macOS; the Bun docs do not specify them.

So a result type should not squeeze everything into one code: number. A child that called exit(143) and a child that was terminated look the same there. Model it as a discriminated union (errors as values): Exited with a code, Signaled with a signal name. Lesson 2 goes into signals.

A pipe holds about 64 KiB. When it is full the child blocks on its next write, until someone reads. If tsbox waits for exited first, or reads stdout to the end and only then stderr, a chatty child and a chatty tsbox wait for each other:

const child = Bun.spawn(["sh", "-c", "yes | head -c 300000 >&2"], { stdout: "pipe", stderr: "pipe" })
// Wrong: stdout never ends until the child exits, and the child cannot exit until stderr is drained.
// const out = await new Response(child.stdout).text()
// const err = await new Response(child.stderr).text()
// Right: drain both at once.
const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
console.log(out.length, err.length)

Bun has a timeout option, but tsbox wants to know the child timed out and to keep its partial output, so it keeps its own timer: start it next to the spawn, call child.kill("SIGKILL") when it fires, and clear it when the child ends first. One trap shows in the tests. sh -c 'echo started; sleep 10' runs sleep as a grandchild. Killing sh does not kill sleep, and sleep still holds the stdout pipe open, so the read never ends. In the test the script ends with exec sleep 10, which replaces the shell with sleep. Killing a whole tree needs process groups, which come back with the container monitor in lesson 6.

Local, because it spawns real programs. Copy main.starter.ts into the Relay project from tooling as main.ts, and the test file next to it. The tests use echo, cat, sh, sleep and bun -e, which exist on macOS and Linux. Run bun test.

run(cmd, options) returns a union: Exited, Signaled, TimedOut, SpawnFailed. The starter builds a shell string, ignores stderr and the timeout, and cannot tell a signal from an exit. The tests check argument passing with hostile input, stdin, env and cwd, a child killed by SIGKILL, a timeout that keeps partial output, and output bigger than a pipe.

main.ts
// Relay's deliver step shells out to `tar`, `git` and friends, and the first version built one shell
// string with user input in it. A source named "x; rm -rf ~" ran as a command. tsbox needs a
// `run(cmd, options)` that takes an argv ARRAY and gives back a typed result. This version has bugs.
//
// Rules (main.test.ts spawns `echo`, `sh`, `cat`, `sleep` and `bun -e`):
// - argv array, never a shell string: arguments containing spaces, quotes, `;` or `$` reach the
// program unchanged.
// - Exited: the exit code, plus all of stdout and stderr as text. A non-zero code is a RESULT, not
// a throw.
// - Signaled: the child died from a signal that nobody asked for; report its name ("SIGKILL").
// - TimedOut: `options.timeoutMs` passed while the child still ran; kill it, keep the output it
// wrote before that, report `afterMs`. A child that finishes in time is not TimedOut.
// - SpawnFailed: the program does not exist. Return the message, do not throw.
// - `options.stdin` is written to the child's stdin and closed; `env` replaces the environment;
// `cwd` sets the working directory.
// - Output larger than a pipe buffer (64 KiB) must not hang the child.
export interface RunOptions {
readonly timeoutMs?: number
readonly cwd?: string
readonly env?: Readonly<Record<string, string>>
readonly stdin?: string
}
interface Output {
readonly stdout: string
readonly stderr: string
}
export type RunResult =
| ({ readonly _tag: "Exited"; readonly code: number } & Output)
| ({ readonly _tag: "Signaled"; readonly signal: string } & Output)
| ({ readonly _tag: "TimedOut"; readonly afterMs: number } & Output)
| { readonly _tag: "SpawnFailed"; readonly message: string }
export async function run(cmd: readonly string[], options: RunOptions = {}): Promise<RunResult> {
const child = Bun.spawn(["sh", "-c", cmd.join(" ")], { cwd: options.cwd, stdout: "pipe" })
const code = await child.exited
const stdout = await new Response(child.stdout).text()
return { _tag: "Exited", code, stdout, stderr: "" }
}
main.test.ts
import { expect, test } from "bun:test"
import { run } from "./main.ts"
const bun = process.execPath
test("stdout, stderr and the exit code come back as one typed result", async () => {
const result = await run([bun, "-e", "console.log('out'); console.error('err'); process.exit(4)"])
expect(result).toEqual({ _tag: "Exited", code: 4, stdout: "out\n", stderr: "err\n" })
})
test("a non-zero exit is a result, not a throw", async () => {
expect(await run(["sh", "-c", "exit 3"])).toEqual({ _tag: "Exited", code: 3, stdout: "", stderr: "" })
})
test("arguments are not parsed by a shell", async () => {
const nasty = "x; echo pwned $HOME 'quoted' \"double\""
const result = await run(["echo", nasty])
expect(result).toEqual({ _tag: "Exited", code: 0, stdout: `${nasty}\n`, stderr: "" })
})
test("stdin is written and closed", async () => {
const result = await run(["cat"], { stdin: "payload" })
expect(result).toEqual({ _tag: "Exited", code: 0, stdout: "payload", stderr: "" })
})
test("env replaces the environment and cwd is honored", async () => {
const result = await run([bun, "-e", "console.log(process.env.RELAY_MODE, process.env.HOME, process.cwd())"], {
env: { RELAY_MODE: "test" },
cwd: "/",
})
expect(result).toEqual({ _tag: "Exited", code: 0, stdout: "test undefined /\n", stderr: "" })
})
test("a child killed by someone else is Signaled", async () => {
const result = await run(["sh", "-c", "kill -KILL $$"])
expect(result).toEqual({ _tag: "Signaled", signal: "SIGKILL", stdout: "", stderr: "" })
})
test("the timeout kills the child and keeps the output written so far", async () => {
const started = performance.now()
const result = await run(["sh", "-c", "echo started; exec sleep 10"], { timeoutMs: 300 })
expect(result).toEqual({ _tag: "TimedOut", afterMs: 300, stdout: "started\n", stderr: "" })
expect(performance.now() - started < 3000).toBe(true)
})
test("a child that finishes before the timeout is not TimedOut", async () => {
const result = await run(["echo", "quick"], { timeoutMs: 5000 })
expect(result).toEqual({ _tag: "Exited", code: 0, stdout: "quick\n", stderr: "" })
})
test("a missing program is SpawnFailed, not a throw", async () => {
const result = await run(["tsbox-no-such-program"])
expect(result._tag).toBe("SpawnFailed")
})
test("large output does not deadlock the child", async () => {
const result = await run([bun, "-e", "process.stdout.write('x'.repeat(300000)); process.stderr.write('y'.repeat(300000))"], {
timeoutMs: 5000,
})
expect(result._tag).toBe("Exited")
if (result._tag === "Exited") expect(result.stdout.length + result.stderr.length).toBe(600000)
})
  • Pass an argv array. Never build a shell string from data.
  • spawn for servers, spawnSync for scripts. A missing program throws; a failing program returns a code.
  • Close stdin when you are done, and drain stdout and stderr together.
  • exited is 128 + n after a signal. signalCode says which signal. Model Exited and Signaled separately.
  • A timeout is your own timer plus kill. Killing a shell does not kill its children.
  • Spawn (Bun): Bun.spawn options, exited and signalCode.