Tooling

Writing small CLI tools in Bun

Argument parsing, colors, exit codes and shipping a single binary: everything you need to turn a script into a tool your team will actually use.

Alex Rivera

· 5 min read

Hand tools hung in rows on a workshop wall

Start with a script

Every useful tool begins life as a script someone ran twice. The moment a third person asks how to run it, it's worth spending an hour to give it a name, a --help and sensible exit codes.

Parsing arguments

Node's built-in parseArgs works in Bun too, and covers most needs without a dependency:

ts
import { parseArgs } from "node:util";const { values, positionals } = parseArgs({  args: Bun.argv.slice(2),  allowPositionals: true,  options: {    out: { type: "string", short: "o", default: "dist" },    watch: { type: "boolean", short: "w" },  },});if (positionals.length === 0) {  console.error("usage: pack <entry> [-o dir] [-w]");  process.exit(2);}

Shipping a binary

bun build --compile bundles your code and the runtime into one executable. No install step for your colleagues, and no question about which Node version they have.

bash
bun build ./src/cli.ts --compile --outfile pack./pack src/index.ts -o build

Keep the tool small and boring. The best internal tools do one thing, print what they did, and exit with a non-zero code when they fail so they compose with everything else.

Keep reading