Bun ShellでJavaScriptからコマンドを実行する方法

​​Bun​TypeScript,シェルスクリプト

Bun の $(Bun Shell)を使うと、await $`ls -l` のように、シェルのコマンドを JavaScript や TypeScript から1行で実行できます。出力は文字列や JSON で受け取れ、コマンドが失敗すれば例外になるので、ふつうの try/catch で扱えます。

ビルドの前に dist フォルダを消す、Git の情報を取り出してファイルに書く、といった作業を、npm scripts やシェルスクリプトではなく TypeScript で書きたいときに向いています。以下、よく使う書き方を、検証環境で実際に出た結果とともに紹介します。

補足

検証環境は Ubuntu 24.04(x86_64)、Bun 1.4.4 です。Windows と macOS、.sh ファイルを bun で直接実行する使い方は試していません。公式ドキュメントは、検証に使った版(タグ bun-v1.4.4)の元ファイルを GitHub で確認し、リンクもそこに張っています。

出力を表示する・文字列で受け取る

$ は bun から import します。Bun に組み込まれているので、パッケージを入れる必要はありません。

ts
import { $ } from "bun";

// そのまま await すると、出力は端末に出る
const shown = await $`echo "Hello, Bun Shell"`;
console.log(shown.exitCode, shown.stdout);

// .text() で文字列として受け取る(端末には出ない)
const text = await $`echo "neko no te"`.text();
console.log(JSON.stringify(text));

// .quiet() は端末への表示だけを止める。結果のオブジェクトは同じように返る
const result = await $`echo "Hello!"`.quiet();
console.log(result.exitCode, result.stdout, result.stderr);
console.log(result.stdout.toString());

bun basic.ts で実行した結果です。

text
Hello, Bun Shell
0 <Buffer 48 65 6c 6c 6f 2c 20 42 75 6e 20 53 68 65 6c 6c 0a>
"neko no te\n"
0 <Buffer 48 65 6c 6c 6f 21 0a> <Buffer >
Hello!

何も付けずに await すると、コマンドの出力がそのまま端末に流れます。await の結果には、終了コード(exitCode)と、Buffer の stdout と stderr が入っていて、文字列にするには toString() を呼びます。.quiet() は端末への表示を止めるだけで、結果は同じように受け取れます。.text() で受け取った文字列には、echo が出した改行(\n)が末尾に残っています(公式ドキュメントの、基本の使い方を説明した節)。

失敗したコマンドは例外になる

終了コードが 0 以外になると、$ は ShellError を投げます。try/catch で受けると、終了コードやエラー出力を取り出せます。

ts
import { $ } from "bun";

try {
  await $`ls nothing-here`.quiet();
} catch (err) {
  if (err instanceof $.ShellError) {
    console.log(`message: ${err.message}`);
    console.log(`exitCode: ${err.exitCode}`);
    console.log(`stderr: ${err.stderr.toString()}`);
  }
}

// .nothrow() を付けると例外にならず、exitCode を自分で見る
const r = await $`no-such-command`.nothrow().quiet();
console.log(`exitCode: ${r.exitCode} stderr: ${r.stderr.toString()}`);
text
message: Failed with exit code 1
exitCode: 1
stderr: ls: nothing-here: No such file or directory

exitCode: 1 stderr: bun: command not found: no-such-command

0 以外の終了コードを失敗として扱いたくない場面では、.nothrow() を付けて exitCode で分けます。存在しないコマンドを呼んだときも、終了コード 1 で bun: command not found が返りました。すべてのコマンドで例外を止めたいときは、$.nothrow() を一度呼んでおく方法もあります(公式ドキュメントのエラー処理の節)。

埋め込んだ変数は、1つの引数として渡る

${} で埋め込んだ値は、空白や ; を含んでいても、1つの引数としてコマンドに渡ります。受け取った引数を1つずつ [ ] で囲んで表示する printf '[%s]\n' で確かめました。

ts
import { $ } from "bun";

// printf '[%s]\n' は、受け取った引数を1つずつ [ ] で囲んで表示する
const input = "my file.txt; rm -rf /";
await $`printf '[%s]\n' ${input}`;

console.log("--- 配列を埋め込む");
const files = ["a b.txt", "c.txt", "*.ts"];
await $`printf '[%s]\n' ${files}`;

console.log("--- テンプレートに直接書いた *.ts");
await $`printf '[%s]\n' *.ts`;
text
[my file.txt; rm -rf /]
--- 配列を埋め込む
[a b.txt]
[c.txt]
[*.ts]
--- テンプレートに直接書いた *.ts
[builtins.ts]
[basic.ts]
[bench.ts]
[unicode.ts]
[envcwd.ts]
[output.ts]
[args.ts]
[errors.ts]

; rm -rf / は次のコマンドとして実行されず、文字列のまま1つの引数になりました。配列を埋め込むと、要素ごとに別の引数になります。埋め込んだ *.ts はそのままの文字で渡り、テンプレートに直接書いた *.ts だけが、フォルダ内のファイル名に展開されました(並び順は名前順ではありませんでした)。

公式ドキュメントでも、埋め込んだ値は1つの文字列として扱うと説明されています。ただし、bash -c のように新しいシェルを起動して文字列を渡すと、この守りは効きません。また、--upload-pack=... のように - で始まる値は、受け取ったコマンドがオプションとして読みます(公式ドキュメントのセキュリティの節)。

コマンドの出力をその場に入れる「コマンド置換」は、$(...) で書きます。テンプレートの中にバッククォートを \` で書いても、置換はされません(公式ドキュメントのコマンド置換の節)。

ts
await $`echo \`echo hi\``;
await $`echo $(echo hi)`;
text
`echo hi`
hi

日本語は、テンプレートに直接書かず ${} で渡す

Bun 1.4.4 では、日本語などの ASCII 以外の文字をテンプレートに直接書くと、コマンドに届く前に \uXXXX の形に変わりました。

ts
import { $ } from "bun";

console.log("--- テンプレートに直接書く");
await $`echo 猫の手`;
await $`echo "猫の手"`;
await $`echo "猫の手" > note.txt`;
console.log(JSON.stringify(await Bun.file("note.txt").text()));

console.log("--- ${} で埋め込む");
const word = "猫の手";
await $`echo ${word}`;
await $`echo ${word} > note.txt`;
console.log(JSON.stringify(await Bun.file("note.txt").text()));
text
--- テンプレートに直接書く
u732Bu306Eu624B
\u732B\u306E\u624B
"\\u732B\\u306E\\u624B\n"
--- ${} で埋め込む
猫の手
"猫の手\n"

引用符なしでは \ まで消えて u732Bu306Eu624B に、引用符で囲むと \u732B\u306E\u624B という文字のまま表示され、ファイルにもその文字で書き込まれました。表示だけの問題ではなく、コマンドが受け取る文字そのものが変わっています。変数に入れて ${} で埋め込むと、正しく 猫の手 になりました。

ファイル名でも同じでした。touch 猫.txt と touch "犬.txt" をテンプレートに直接書き、鳥.txt だけを変数で渡したところ、できたファイルは次の3つです。

ts
import { $ } from "bun";

await $`mkdir -p names && cd names && touch 猫.txt && touch "犬.txt"`;
const word = "鳥.txt";
await $`touch ${word}`.cwd("names");
await $`ls names`;
await $`rm -rf names`;
text
鳥.txt
\u72AC.txt
u732B.txt

これは公開の不具合報告にある現象です。Bun のトランスパイラーが、タグ付きテンプレートの raw の中の ASCII 以外の文字を \uXXXX に置き換えていて、$ はその raw を読むため、と Bun のチームが説明しています(Issue #18859 にある、原因についてのコメント)。元の不具合(Issue #8745)は、2026年11月14日の時点で未解決です。

注意

ASCII 以外の文字は、テンプレートに直接書かず、必ず変数に入れて ${} で渡してください。

パイプ、JSON、ファイルへの書き出し

パイプ(|)やリダイレクト(<、>)は、bash と同じように書けます(公式ドキュメントのパイプの節)。そのうえで、受け取り方や入出力先に JavaScript のオブジェクトを使えます。list.txt には apple、banana、bun、bunny の4行を、package.json には name と version だけを書いておきました。

ts
import { $ } from "bun";

// パイプでつなぎ、1行ずつ受け取る
for await (const line of $`cat list.txt | grep ${"bun"}`.lines()) {
  console.log(`line: ${JSON.stringify(line)}`);
}

// 出力を JSON として受け取る
const pkg = await $`cat package.json`.json();
console.log(pkg.name, pkg.version);

// Response を標準入力にする
const res = new Response("hello from response");
console.log(await $`cat < ${res} | wc -c`.text());

// 出力を Buffer と Bun.file に書き出す
const buf = Buffer.alloc(20);
await $`echo "Hello World!" > ${buf}`;
console.log(JSON.stringify(buf.toString()));

await $`echo "bun!" > ${Bun.file("greeting.txt")}`;
console.log(JSON.stringify(await Bun.file("greeting.txt").text()));
text
line: "bun"
line: "bunny"
line: ""
shell-demo 1.0.0
19

"Hello World!\n\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
"bun!\n"

.lines() は、出力の最後の改行のあとに、空の文字列を1行ぶん返しました。行ごとに処理するときは、空の行を飛ばす if (!line) continue; を入れておくと安心です。.json() は、出力を JSON として読み取った値を返します(公式ドキュメントの、出力の受け取り方の節)。

Buffer に書き出すと、20バイトのうち出力が入らなかった残りは \u0000(0 のバイト)のままでした。Bun.file() に書き出すと、ファイルに出力が保存されます。入出力に使える JavaScript のオブジェクトの一覧は、公式ドキュメントのリダイレクトの節にあります。

環境変数と作業フォルダを、コマンドごとに変える

環境変数は、bash と同じく NAME=値 コマンド の形で渡せます。コマンドごとに変えるなら .env()、作業フォルダは .cwd() で指定します。

ts
import { $ } from "bun";

const name = "猫 の 手; echo injected";
await $`NAME=${name} bun -e 'console.log(process.env.NAME)'`;

await $`echo "FOO=$FOO"`.env({ ...process.env, FOO: "bar" });
await $`echo "FOO=$FOO"`;

await $`pwd`.cwd("/tmp");
await $`cd /tmp && pwd`;
await $`pwd`;
console.log(`process.cwd(): ${process.cwd()}`);
text
猫 の 手; echo injected
FOO=bar
FOO=
/tmp
/tmp
/path/to/app
process.cwd(): /path/to/app

(作業フォルダのパスは /path/to/app に置き換えています。)

テンプレートの中で cd しても、次の $ の作業フォルダや、スクリプトの process.cwd() は元のままでした。.env() で渡した FOO は、そのコマンドの中だけで使われ、次のコマンドでは空でした。.env() に渡したオブジェクトが環境変数のすべてになります。.env({ FOO: "bar" }) だけを渡して $HOME を表示すると、空になりました。PATH や HOME などを残したいときは ...process.env を一緒に渡します。

ts
import { $ } from "bun";

await $`echo "HOME=$HOME FOO=$FOO"`;
await $`echo "HOME=$HOME FOO=$FOO"`.env({ FOO: "bar" });
await $`echo "HOME=$HOME FOO=$FOO"`.env({ ...process.env, FOO: "bar" });
text
HOME=/path/to/home FOO=
HOME= FOO=bar
HOME=/path/to/home FOO=bar

(HOME の値は /path/to/home に置き換えています。)

すべてのコマンドの既定を変えたいときは、$.env() と $.cwd() を使います(公式ドキュメントの、環境変数と作業フォルダの節)。

ls や rm は、Bun が自前で実行する

Bun Shell は /bin/sh を呼ばず、Bun のプロセスの中でコマンドを解釈します(公式ドキュメントのセキュリティの節の冒頭)。ls、rm、mkdir、cat などのよく使うコマンドは、Bun の組み込みとして用意されています(公式ドキュメントの組み込みコマンドの一覧)。

ts
import { $ } from "bun";

console.log("--- Bun Shell の ls と、/usr/bin/ls");
const a = await $`ls nothing-here`.nothrow();
console.log(`exitCode: ${a.exitCode}`);
const b = await $`/usr/bin/ls nothing-here`.nothrow();
console.log(`exitCode: ${b.exitCode}`);

console.log("--- PATH を空にして実行");
const c = await $`mkdir -p dist/js && touch dist/js/app.js && ls dist/js && rm -rf dist && ls`
  .env({ PATH: "" })
  .nothrow();
console.log(`exitCode: ${c.exitCode}`);
const d = await $`printf hi`.env({ PATH: "" }).nothrow();
console.log(`exitCode: ${d.exitCode}`);
text
--- Bun Shell の ls と、/usr/bin/ls
ls: nothing-here: No such file or directory
exitCode: 1
/usr/bin/ls: cannot access 'nothing-here': No such file or directory
exitCode: 2
--- PATH を空にして実行
app.js
builtins.ts
note.txt
list.txt
(作業フォルダのファイルが続くため、以下は省略)
exitCode: 0
bun: command not found: printf
exitCode: 1

同じ ls でも、Bun Shell の組み込みと Ubuntu の /usr/bin/ls(GNU coreutils 9.4)では、エラーの文言も終了コード(1 と 2)も違いました。終了コードの値で処理を分けるスクリプトを移すときは、この違いに気をつけます。

PATH を空にすると、組み込みの mkdir -p、touch、ls、rm -rf は動き、dist フォルダを作って消すところまで終了コード 0 で通りました。組み込みにない printf は、command not found になりました。

組み込みの echo は200回で5ms、/usr/bin/echo は約200msだった

組み込みのコマンドと、外部のコマンドを何度も呼んだときの差を測りました。echo hi を200回ずつ実行して時間を測り、続けて sleep 1 を3つ、順番に await した場合と Promise.all でまとめた場合を比べました。

ts
import { $ } from "bun";

const N = 200;
async function bench(label: string, fn: () => Promise<unknown>) {
  const t = performance.now();
  for (let i = 0; i < N; i++) await fn();
  const ms = performance.now() - t;
  console.log(`${label}: ${N}回で ${ms.toFixed(0)}ms(1回あたり ${(ms / N).toFixed(2)}ms)`);
}
await bench("組み込みの echo", () => $`echo hi`.quiet());
await bench("/usr/bin/echo", () => $`/usr/bin/echo hi`.quiet());

let t = performance.now();
await $`sleep 1`;
await $`sleep 1`;
await $`sleep 1`;
console.log(`1つずつ await: ${(performance.now() - t).toFixed(0)}ms`);

t = performance.now();
await Promise.all([$`sleep 1`, $`sleep 1`, $`sleep 1`]);
console.log(`Promise.all: ${(performance.now() - t).toFixed(0)}ms`);

3回実行した結果です。

測ったもの 1回目 2回目 3回目
組み込みの echo(200回) 5ms 5ms 5ms
/usr/bin/echo(200回) 197ms 199ms 198ms
sleep 1 を1つずつ await 3005ms 3006ms 3005ms
sleep 1 を Promise.all 1002ms 1003ms 1002ms

組み込みの echo は1回あたり 0.02〜0.03ms、/usr/bin/echo は 0.98〜1.00ms でした。Promise.all に渡したコマンドは同時に動き、3秒かかっていた処理が約1秒で終わりました。互いに関係のない処理(複数のフォルダの掃除など)は、まとめて実行できます。

​Posted by 86