Skip to main content
Bun Shell 是内置于 Bun 的跨平台类 bash shell。 它提供了一种在 JavaScript 和 TypeScript 中运行 shell 命令的简便方式。要开始使用,请从 bun 包中导入 $ 函数,并使用它来运行 shell 命令。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260afoo.ts
import { $ } from "bun";

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

$ 函数是一个标签模板字面量,用于执行命令并返回一个解析为命令输出的 Promise。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260afoo.ts
import { $ } from "bun";

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

要将输出的每一行作为数组获取,请使用 lines 方法。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260afoo.ts
import { $ } from "bun";

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

完整文档请参见 文档 > API > Shell