執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

執行 Shell 命令

Bun Shell 是內置於 Bun 中的跨平臺類 bash shell。

它可以從 JavaScript 和 TypeScript 中執行 shell 命令。要開始使用,請從 bun 包中匯入 $ 函式。

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

await $`echo Hello, world!`; // => "你好,世界!"

$ 函式是一個標籤模板字面量,用於執行命令並傳回一個 Promise,該 Promise 會解析為命令輸出。

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

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

要遍歷輸出中的每一行,請使用 lines 方法。

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

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

請參閱 Bun Shell。