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

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

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

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

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

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

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