Bun Shell ($) is a cross-platform shell built into Bun that lets you run shell commands directly in JavaScript/TypeScript. It's not just a child_process wrapper — it's a full shell with pipes, redirects, and globbing that works identically on macOS, Linux, and Windows.
What Makes Bun Shell Special?
- Cross-platform — same scripts work on macOS, Linux, Windows
- Template literals — write shell commands as tagged templates
- JavaScript interop — pipe between JS and shell seamlessly
- Built-in — no npm install, comes with Bun
The Hidden API: Shell-JavaScript Bridge
import { $ } from 'bun';
// Run shell commands with template literals
const result = await $`echo hello world`;
console.log(result.text()); // 'hello world\n'
// Pipe shell output to JavaScript
const files = await $`ls -la src/`.text();
const tsFiles = files.split('\n').filter(f => f.endsWith('.ts'));
// Pipe JavaScript to shell
const data = JSON.stringify({ name: 'test', value: 42 });
await $`echo ${data} | jq .name`;
// Chain commands
await $`cat package.json | jq .dependencies | sort`;
Advanced Piping API
// Pipe between shell and Response objects
const resp = await fetch('https://api.github.com/repos/oven-sh/bun');
await $`echo ${resp} | jq .stargazers_count`;
// Write to files
await $`echo "Hello" > output.txt`;
await $`cat input.txt >> output.txt`;
// Glob support
const count = await $`wc -l src/**/*.ts`.text();
console.log('Total lines:', count);
Error Handling
import { $ } from 'bun';
try {
await $`exit 1`;
} catch (err) {
console.log('Exit code:', err.exitCode);
console.log('stderr:', err.stderr.toString());
}
// Or use .nothrow() to handle errors yourself
const result = await $`might-fail`.nothrow();
if (result.exitCode !== 0) {
console.log('Failed:', result.stderr.toString());
}
Build Scripts Made Easy
// build.ts — cross-platform build script
import { $ } from 'bun';
await $`rm -rf dist`;
await $`mkdir -p dist`;
await $`bun build src/index.ts --outdir dist --minify`;
await $`cp package.json dist/`;
await $`echo "Build complete!"`;
// Run tests in parallel
await Promise.all([
$`bun test src/utils/`,
$`bun test src/api/`,
$`bun test src/components/`,
]);
Quick Start
# Install Bun
curl -fsSL https://bun.sh/install | bash
# Use $ in any .ts file
bun run build.ts
Why Developers Love Bun Shell
A DevOps engineer shared: "We replaced 15 bash scripts with Bun Shell. Same functionality, but now it works on our Windows CI runner too. And we get TypeScript autocomplete for the JavaScript parts."
Need automation scripts or data tools? Email spinov001@gmail.com or check my automation toolkit.
Using Bun? What do you think of the shell API?
Top comments (0)