npx skills add https://github.com/secondsky/claude-skills --skill 'Bun Shell'Bun 提供了强大的 shell 脚本功能,支持模板字面量和 spawn API。
import { $ } from "bun";
// 运行命令
await $`echo "Hello World"`;
// 获取输出
const result = await $`ls -la`.text();
console.log(result);
// JSON 输出
const pkg = await $`cat package.json`.json();
console.log(pkg.name);
import { $ } from "bun";
const name = "world";
const dir = "./src";
// 安全插值(已转义)
await $`echo "Hello ${name}"`;
await $`ls ${dir}`;
// 数组展开
const files = ["a.txt", "b.txt", "c.txt"];
await $`touch ${files}`;
import { $ } from "bun";
// 管道命令
const result = await $`cat file.txt | grep "pattern" | wc -l`.text();
// 与 JavaScript 链式调用
const files = await $`ls -la`.text();
const lines = files.split("\n").filter(line => line.includes(".ts"));
import { $ } from "bun";
// 非零退出时抛出异常
try {
await $`exit 1`;
} catch (err) {
console.log(err.exitCode); // 1
console.log(err.stderr);
}
// 静默模式(不抛出异常)
const result = await $`exit 1`.quiet();
console.log(result.exitCode); // 1
// 检查退出码
const { exitCode } = await $`grep pattern file.txt`.quiet();
if (exitCode !== 0) {
console.log("Pattern not found");
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
import { $ } from "bun";
// 文本
const text = await $`echo hello`.text();
// JSON
const json = await $`cat data.json`.json();
// 行
const lines = await $`ls`.lines();
// Blob
const blob = await $`cat image.png`.blob();
// ArrayBuffer
const buffer = await $`cat binary.dat`.arrayBuffer();
import { $ } from "bun";
// 为命令设置环境变量
await $`echo $MY_VAR`.env({ MY_VAR: "value" });
// 访问当前环境变量
$.env.MY_VAR = "value";
await $`echo $MY_VAR`;
// 清除环境变量
await $`env`.env({});
import { $ } from "bun";
// 为命令更改目录
await $`pwd`.cwd("/tmp");
// 或全局设置
$.cwd("/tmp");
await $`pwd`;
const proc = Bun.spawn(["echo", "Hello World"]);
const output = await new Response(proc.stdout).text();
console.log(output); // "Hello World\n"
const proc = Bun.spawn(["node", "script.js"], {
cwd: "./project",
env: {
NODE_ENV: "production",
...process.env,
},
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});
// 写入 stdin
proc.stdin.write("input data\n");
proc.stdin.end();
// 读取 stdout
const output = await new Response(proc.stdout).text();
const errors = await new Response(proc.stderr).text();
// 等待退出
const exitCode = await proc.exited;
// 继承(使用父进程的 stdio)
Bun.spawn(["ls"], { stdio: ["inherit", "inherit", "inherit"] });
// 管道(捕获输出)
Bun.spawn(["ls"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" });
// 空(忽略)
Bun.spawn(["ls"], { stdout: null, stderr: null });
// 文件(重定向到文件)
Bun.spawn(["ls"], {
stdout: Bun.file("output.txt"),
stderr: Bun.file("errors.txt"),
});
const proc = Bun.spawn(["tail", "-f", "log.txt"], {
stdout: "pipe",
});
const reader = proc.stdout.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(new TextDecoder().decode(value));
}
// 同步执行
const result = Bun.spawnSync(["ls", "-la"]);
console.log(result.exitCode);
console.log(result.stdout.toString());
console.log(result.stderr.toString());
console.log(result.success); // exitCode === 0
#!/usr/bin/env bun
import { $ } from "bun";
// 脚本逻辑
const branch = await $`git branch --show-current`.text();
console.log(`Current branch: ${branch.trim()}`);
await $`npm test`;
await $`npm run build`;
chmod +x script.ts
./script.ts
#!/usr/bin/env bun
import { $ } from "bun";
async function deploy() {
console.log("🚀 Starting deployment...");
// 检查未提交的更改
const status = await $`git status --porcelain`.text();
if (status.trim()) {
console.error("❌ Uncommitted changes found!");
process.exit(1);
}
// 运行测试
console.log("🧪 Running tests...");
await $`bun test`;
// 构建
console.log("🏗️ Building...");
await $`bun run build`;
// 部署
console.log("📦 Deploying...");
await $`rsync -avz ./dist/ server:/app/`;
console.log("✅ Deployment complete!");
}
deploy().catch((err) => {
console.error("❌ Deployment failed:", err);
process.exit(1);
});
import { $ } from "bun";
// 并行运行
await Promise.all([
$`npm run lint`,
$`npm run typecheck`,
$`npm run test`,
]);
// 或使用 spawn
const procs = [
Bun.spawn(["npm", "run", "lint"]),
Bun.spawn(["npm", "run", "typecheck"]),
Bun.spawn(["npm", "run", "test"]),
];
await Promise.all(procs.map(p => p.exited));
import { $ } from "bun";
// 传递 stdin
const proc = Bun.spawn(["node"], {
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
});
await proc.exited;
const proc = Bun.spawn(["long-running-process"]);
// 终止进程
proc.kill(); // SIGTERM
proc.kill("SIGKILL"); // 强制终止
// 检查是否在运行
console.log(proc.killed);
// 获取 PID
console.log(proc.pid);
// 带超时等待
const timeout = setTimeout(() => proc.kill(), 5000);
await proc.exited;
clearTimeout(timeout);
import { $ } from "bun";
await $`bun run build`;
await $`bun test`;
await $`bunx tsc --noEmit`;
import { $ } from "bun";
const branch = await $`git branch --show-current`.text();
const commit = await $`git rev-parse HEAD`.text();
const status = await $`git status --short`.text();
if (status) {
await $`git add -A`;
await $`git commit -m "Auto commit"`;
}
import { $ } from "bun";
// 查找文件
const files = await $`find . -name "*.ts"`.lines();
// 搜索内容
const matches = await $`grep -r "TODO" src/`.text();
// 归档
await $`tar -czf backup.tar.gz ./data`;
| 错误 | 原因 | 解决方法 |
|---|---|---|
Command not found | 不在 PATH 中 | 使用绝对路径 |
Permission denied | 不可执行 | chmod +x |
Exit code 1 | 命令失败 | 检查 stderr |
EPIPE | 管道损坏 | 处理进程退出 |
当遇到以下情况时加载 references/advanced-scripting.md:
当遇到以下情况时加载 references/cross-platform.md:
每周安装次数
–
代码仓库
GitHub 星标数
90
首次出现时间
–
安全审计
Bun provides powerful shell scripting capabilities with template literals and spawn APIs.
import { $ } from "bun";
// Run command
await $`echo "Hello World"`;
// Get output
const result = await $`ls -la`.text();
console.log(result);
// JSON output
const pkg = await $`cat package.json`.json();
console.log(pkg.name);
import { $ } from "bun";
const name = "world";
const dir = "./src";
// Safe interpolation (escaped)
await $`echo "Hello ${name}"`;
await $`ls ${dir}`;
// Array expansion
const files = ["a.txt", "b.txt", "c.txt"];
await $`touch ${files}`;
import { $ } from "bun";
// Pipe commands
const result = await $`cat file.txt | grep "pattern" | wc -l`.text();
// Chain with JavaScript
const files = await $`ls -la`.text();
const lines = files.split("\n").filter(line => line.includes(".ts"));
import { $ } from "bun";
// Throws on non-zero exit
try {
await $`exit 1`;
} catch (err) {
console.log(err.exitCode); // 1
console.log(err.stderr);
}
// Quiet mode (no throw)
const result = await $`exit 1`.quiet();
console.log(result.exitCode); // 1
// Check exit code
const { exitCode } = await $`grep pattern file.txt`.quiet();
if (exitCode !== 0) {
console.log("Pattern not found");
}
import { $ } from "bun";
// Text
const text = await $`echo hello`.text();
// JSON
const json = await $`cat data.json`.json();
// Lines
const lines = await $`ls`.lines();
// Blob
const blob = await $`cat image.png`.blob();
// ArrayBuffer
const buffer = await $`cat binary.dat`.arrayBuffer();
import { $ } from "bun";
// Set env for command
await $`echo $MY_VAR`.env({ MY_VAR: "value" });
// Access current env
$.env.MY_VAR = "value";
await $`echo $MY_VAR`;
// Clear env
await $`env`.env({});
import { $ } from "bun";
// Change directory for command
await $`pwd`.cwd("/tmp");
// Or globally
$.cwd("/tmp");
await $`pwd`;
const proc = Bun.spawn(["echo", "Hello World"]);
const output = await new Response(proc.stdout).text();
console.log(output); // "Hello World\n"
const proc = Bun.spawn(["node", "script.js"], {
cwd: "./project",
env: {
NODE_ENV: "production",
...process.env,
},
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});
// Write to stdin
proc.stdin.write("input data\n");
proc.stdin.end();
// Read stdout
const output = await new Response(proc.stdout).text();
const errors = await new Response(proc.stderr).text();
// Wait for exit
const exitCode = await proc.exited;
// Inherit (use parent's stdio)
Bun.spawn(["ls"], { stdio: ["inherit", "inherit", "inherit"] });
// Pipe (capture output)
Bun.spawn(["ls"], { stdin: "pipe", stdout: "pipe", stderr: "pipe" });
// Null (ignore)
Bun.spawn(["ls"], { stdout: null, stderr: null });
// File (redirect to file)
Bun.spawn(["ls"], {
stdout: Bun.file("output.txt"),
stderr: Bun.file("errors.txt"),
});
const proc = Bun.spawn(["tail", "-f", "log.txt"], {
stdout: "pipe",
});
const reader = proc.stdout.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(new TextDecoder().decode(value));
}
// Synchronous execution
const result = Bun.spawnSync(["ls", "-la"]);
console.log(result.exitCode);
console.log(result.stdout.toString());
console.log(result.stderr.toString());
console.log(result.success); // exitCode === 0
#!/usr/bin/env bun
import { $ } from "bun";
// Script logic
const branch = await $`git branch --show-current`.text();
console.log(`Current branch: ${branch.trim()}`);
await $`npm test`;
await $`npm run build`;
chmod +x script.ts
./script.ts
#!/usr/bin/env bun
import { $ } from "bun";
async function deploy() {
console.log("🚀 Starting deployment...");
// Check for uncommitted changes
const status = await $`git status --porcelain`.text();
if (status.trim()) {
console.error("❌ Uncommitted changes found!");
process.exit(1);
}
// Run tests
console.log("🧪 Running tests...");
await $`bun test`;
// Build
console.log("🏗️ Building...");
await $`bun run build`;
// Deploy
console.log("📦 Deploying...");
await $`rsync -avz ./dist/ server:/app/`;
console.log("✅ Deployment complete!");
}
deploy().catch((err) => {
console.error("❌ Deployment failed:", err);
process.exit(1);
});
import { $ } from "bun";
// Run in parallel
await Promise.all([
$`npm run lint`,
$`npm run typecheck`,
$`npm run test`,
]);
// Or with spawn
const procs = [
Bun.spawn(["npm", "run", "lint"]),
Bun.spawn(["npm", "run", "typecheck"]),
Bun.spawn(["npm", "run", "test"]),
];
await Promise.all(procs.map(p => p.exited));
import { $ } from "bun";
// Pass through stdin
const proc = Bun.spawn(["node"], {
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
});
await proc.exited;
const proc = Bun.spawn(["long-running-process"]);
// Kill process
proc.kill(); // SIGTERM
proc.kill("SIGKILL"); // Force kill
// Check if running
console.log(proc.killed);
// Get PID
console.log(proc.pid);
// Wait with timeout
const timeout = setTimeout(() => proc.kill(), 5000);
await proc.exited;
clearTimeout(timeout);
import { $ } from "bun";
await $`bun run build`;
await $`bun test`;
await $`bunx tsc --noEmit`;
import { $ } from "bun";
const branch = await $`git branch --show-current`.text();
const commit = await $`git rev-parse HEAD`.text();
const status = await $`git status --short`.text();
if (status) {
await $`git add -A`;
await $`git commit -m "Auto commit"`;
}
import { $ } from "bun";
// Find files
const files = await $`find . -name "*.ts"`.lines();
// Search content
const matches = await $`grep -r "TODO" src/`.text();
// Archive
await $`tar -czf backup.tar.gz ./data`;
| Error | Cause | Fix |
|---|---|---|
Command not found | Not in PATH | Use absolute path |
Permission denied | Not executable | chmod +x |
Exit code 1 | Command failed | Check stderr |
EPIPE | Broken pipe | Handle process exit |
Load references/advanced-scripting.md when:
Load references/cross-platform.md when:
Weekly Installs
–
Repository
GitHub Stars
90
First Seen
–
Security Audits
Skills CLI 使用指南:AI Agent 技能包管理器安装与管理教程
27,400 周安装