blog.dopana

Back

Bun Shell is a cross-platform, bash-like shell built directly into the Bun runtime. It enables developers to execute shell commands seamlessly within JavaScript and TypeScript without relying on external dependencies or third-party packages.

Getting Started with Bun Shell#

To start using Bun Shell, import the $ function from the bun package. The $ function is a tagged template literal that executes the given command and returns a promise resolving with the output.

index.ts
import { $ } from "bun";

await $`echo Hello, world!`; // => "Hello, world!"
ts

Reading Command Output#

You can extract the full standard output as a string by calling the .text() method:

index.ts
import { $ } from "bun";

const output = await $`ls -l`.text();
console.log(output);
ts

Iterating Over Lines with lines()#

To process command output line by line, use the .lines() method combined with an asynchronous for await...of loop:

index.ts
import { $ } from "bun";

for await (const line of $`ls -l`.lines()) {
  console.log(line);
}
ts

References#