Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท File I/O, SQLite and Data

Bun Shell and Child Processes

Run commands from JavaScript with the Bun Shell tagged template and Bun.spawn: safe interpolation, pipes, output helpers, exit codes, environment, working directory and streaming output.

Scripts often need to run other programs: build a folder, call git, convert an image, start a database. In Node you reach for child_process, and you quickly meet quoting problems and differences between Windows and Linux. Bun gives you two tools. The Bun Shell ($) is a small cross-platform shell implemented in Bun itself, written as a tagged template. Bun.spawn is the lower-level API for starting a process with full control of its input and output streams.

Bun is not available here, so $ and Bun.spawn code is read-only. The TryIt blocks run real processes through Node's child_process (starting Node itself so they work everywhere) to show the same ideas: exit codes, captured output, safe argument passing. They are stand-ins.

The Bun Shell

TypeScript
import { $ } from "bun";

await $`echo "Hello from the Bun Shell"`;

By default the command's output goes to your terminal. To use it in code, call a reader on the promise:

TypeScript
const branch = await $`git branch --show-current`.text();      // string, includes trailing newline
const pkg = await $`cat package.json`.json();                    // parsed JSON
for await (const line of $`ls -1`.lines()) console.log(line);    // line by line
const { stdout, stderr, exitCode } = await $`ls`.quiet();        // Buffer results, no echo

.quiet() stops output from printing. .text() and .json() already imply it. Beyond calling programs, the shell understands the usual syntax:

TypeScript
await $`cat logs/app.log | grep ERROR | wc -l`;          // pipes
await $`echo "build ok" > out/status.txt`;                // redirect to a file
await $`ls *.ts`;                                         // globs
await $`mkdir -p dist && cp -r public/* dist/`;           // && chains
await $`rm -rf dist`;
await $`cd src && ls`;                                     // cd only affects this command

Common commands (ls, cd, cat, echo, mkdir, rm, mv, touch, which, pwd, basename, dirname, seq, true, false, exit) are implemented inside Bun, so scripts behave the same on Windows, macOS and Linux. Other programs (git, docker, ffmpeg) must be installed and on PATH.

Safe interpolation

Values you put in ${...} are escaped as a single argument, so a hostile string cannot inject commands:

TypeScript
const filename = "my file; rm -rf /.txt";
await $`touch ${filename}`; // creates ONE file with that odd name, runs nothing else

const files = ["a.txt", "b.txt"];
await $`cat ${files}`;      // arrays become separate arguments

That is a big safety win over building a command with string concatenation and passing it to a shell. Use { raw: "..." } only for trusted text that must be interpreted as shell syntax.

Errors, exit codes and environment

If a command exits with a non-zero code, awaiting it throws a ShellError:

TypeScript
try {
  await $`ls /does/not/exist`.quiet();
} catch (err) {
  console.log(err.exitCode);        // 1 or 2 depending on the platform
  console.log(err.stderr.toString());
}

const result = await $`grep needle haystack.txt`.nothrow().quiet(); // no throw
if (result.exitCode === 0) console.log("found");

$.throws(false);                    // switch throwing off globally for this module

Set the environment and working directory per command: $\node app.js`.env({ ...process.env, NODE_ENV: "production" }).cwd("./server"). Use $.env(...)or$.cwd(...)` to change the defaults for all later commands.

Node.js Exit codes, captured output and safe arguments (child_process stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Bun.spawn: full control

Bun.spawn takes an array (command and arguments, never parsed by a shell) and returns a Subprocess right away:

TypeScript
const proc = Bun.spawn(["git", "log", "--oneline", "-5"], {
  cwd: "./repo",
  env: { ...process.env, GIT_PAGER: "cat" },
  stdout: "pipe",   // "pipe" | "inherit" | "ignore" | a file | a ReadableStream
  stderr: "pipe",
});

const output = await new Response(proc.stdout).text();   // read the stream
const code = await proc.exited;                          // promise for the exit code
console.log(code, output);

Important members of a Subprocess: proc.stdout / proc.stderr (a ReadableStream when set to "pipe"), proc.stdin (a writable sink when stdin: "pipe"), proc.exited (promise), proc.exitCode, proc.pid, proc.kill() and proc.signalCode. Other options include timeout and onExit(proc, exitCode, signalCode, error).

To feed input:

TypeScript
const proc = Bun.spawn(["wc", "-w"], { stdin: "pipe", stdout: "pipe" });
proc.stdin.write("one two three");
proc.stdin.end();
console.log(await new Response(proc.stdout).text()); // "3"

Bun.spawnSync(cmd, opts) blocks until the process finishes and returns { stdout, stderr, exitCode, success } with Buffers: simple for build scripts, but it blocks the event loop, so never use it inside a request handler.

Choosing between them

Need Use
Quick script, pipes, globs, cross-platform behavior $
Streaming a long process's output, writing to its stdin, killing it Bun.spawn
A blocking helper in a CLI or build step Bun.spawnSync
An untrusted value inside a command either, but never string-built shell text

Streaming output of a long process

For a build or a dev server you want to forward output as it arrives instead of waiting for the end. With Bun.spawn, set stdout: "inherit" to connect it directly to your terminal, or iterate the stream:

TypeScript
const proc = Bun.spawn(["bun", "run", "build"], { stdout: "pipe" });
for await (const chunk of proc.stdout) {
  process.stdout.write(chunk);
}
await proc.exited;
Node.js Streaming a child's output as it arrives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Practical script: a release helper

TypeScript
#!/usr/bin/env bun
import { $ } from "bun";

const status = await $`git status --porcelain`.text();
if (status.trim() !== "") {
  console.error("Working tree is dirty. Commit or stash first.");
  process.exit(1);
}

await $`bun test`;
await $`bun run build`;
const version = (await Bun.file("package.json").json()).version;
await $`git tag v${version}`;
console.log(`Tagged v${version}`);

A file with #!/usr/bin/env bun on line 1 and the executable bit runs directly: ./release.ts. More on shipping scripts in scripts and CLIs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a value interpolated as ${name} inside a Bun Shell template?

    Interpolated values are escaped, which prevents command injection.
  2. 2. What does awaiting a Bun Shell command do when it exits with a non-zero code?

    Failures throw by default; use .nothrow() or $.throws(false) to inspect the exit code instead.
  3. 3. Which API should you use to write to a running process's stdin and stream its stdout?

    Bun.spawn exposes the process streams; .text() only returns the final output.
  4. 4. Why avoid Bun.spawnSync in a request handler?

    A synchronous call stops all other requests until it returns.

Summary

  • $ runs commands as tagged templates with pipes, redirects, globs and built-in cross-platform commands.
  • Interpolation is escaped; use .text(), .json(), .lines(), .quiet() to read results.
  • Non-zero exit codes throw; use .nothrow() to handle them.
  • Bun.spawn([cmd, ...args], options) gives streams, exited, kill(); spawnSync blocks.
  • Treat command arguments as data and never build shell strings from user input.

Next: Passwords, Hashing, Environment and Other Data Clients