关于 claude-code-bash-patterns
claude-code-bash-patterns 是介绍 Claude Code Bash 工具用法的参考技能,涵盖命令组合、Shell 钩子、Git 工作流和 CLI 使用。它面向希望采用可复用命令行模式并通过钩子设置防护的 Claude Code 用户。
主要功能
- 01命令串联与条件执行
- 02并行命令执行指南
- 03Heredoc 与输出处理模式
- 04工具调用前后钩子示例
- 05Git 与 CLI 工作流指南
- 06危险命令拦截配置
适用场景
- 01按依赖关系执行构建与测试
- 02通过钩子记录或阻止 Bash 调用
- 03收集 Git 信息并准备提交
- 04使用 gh 创建拉取请求
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill claude-code-bash-patterns安装后在 Claude Code 中输入/claude-code-bash-patterns确认已加载。
附带文件README.mdSKILL.json
详细介绍
Claude Code Bash 模式
状态:已可投入生产 ✅ 最后更新:2025-11-07 依赖项:Claude Code CLI(最新版本) 官方文档:https://docs.claude.com/en/docs/claude-code/tools
快速入门(10 分钟)
1. 了解 Bash 工具
Bash 工具是 Claude Code 执行命令行操作的主要接口。与专用工具(Read、Grep、Glob)不同,Bash 工具可直接访问 shell,以执行复杂的工作流。
主要特点:
- 会话持久性:命令会在对话中的持久 bash 会话内运行
- 环境继承:继承环境变量和工作目录
- 输出限制:输出超过 30,000 个字符时会被截断
- 默认超时:2 分钟(可配置,最长 10 分钟)
适用场景:
- ✅ 运行 CLI 工具(git、npm、wrangler、gh 等)
- ✅ 命令串联(顺序执行操作)
- ✅ 流程编排(构建、测试、部署)
- ✅ 环境设置和管理
不适用场景:
- ❌ 读取文件 → 请改用 Read 工具
- ❌ 搜索文件模式 → 请改用 Glob 工具
- ❌ 搜索内容 → 请改用 Grep 工具
- ❌ 编辑文件 → 请改用 Edit 工具
2. 基本命令模式
# Single command
npm install
# Sequential with && (stops on first failure)
npm install && npm run build
# Sequential with ; (continues regardless)
npm install ; npm run build
# Parallel execution (make multiple Bash tool calls)
# Call 1: git status
# Call 2: git diff
# Call 3: git log
黄金法则:关注失败时使用 &&,不关注失败时使用 ;,操作互不依赖时使用并行调用。
3. 配置第一个钩子
钩子可以在工具执行前后运行代码。下面是一个简单的审计日志记录器:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo \"[$(date -Iseconds)] $(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.command')\" >> ~/.claude/bash-audit.log"
}
]
}
]
}
}
将其保存到 ~/.claude/settings.json,即可记录每条 bash 命令及其时间戳。
五种核心模式
模式 1:命令串联
适用场景:按顺序执行操作,且每个操作都依赖前一个操作成功
语法:command1 && command2 && command3
示例:构建和部署工作流
npm install && npm run build && npx wrangler deploy
重要性:
- 首次失败时停止(防止错误连锁发生)
- 保持错误消息清晰(准确知道失败之处)
- 节省令牌(无需在命令之间检查状态)
反面模式:关注失败时使用 ;
# ❌ Wrong: Continues even if install fails
npm install ; npm run build
# ✅ Correct: Stops if install fails
npm install && npm run build
进阶用法:使用 || 条件执行
# Run tests, or echo failure message
npm test || echo "Tests failed, not deploying"
# Try npm ci, fall back to npm install
npm ci || npm install
模式 2:并行执行
适用场景:可同时运行的互不依赖的操作
方法:在同一条消息中发起多次 Bash 工具调用
示例:Git 工作流的提交前分析
# Claude makes 3 parallel Bash calls in one message:
Call 1: git status
Call 2: git diff --staged
Call 3: git log -5 --oneline
优势:
- 比顺序执行快约 40%(调用之间无需等待)
- 减少上下文用量(所有结果同时返回)
- 用户体验更佳(看起来即时完成)
重要提示:仅并行执行真正互不依赖的操作。如果调用 2 依赖调用 1 的输出,请按顺序执行。
模式 3:多行内容的 HEREDOC
适用场景:Git 提交、创建文件、包含换行符的复杂字符串
语法:cat <<'EOF' ... EOF
示例:使用详细消息进行 Git 提交
git commit -m "$(cat <<'EOF'
feat(auth): Add JWT verification middleware
Implement custom JWT template support for Clerk auth.
Extracts email and metadata claims for user context.
🤖 Generated with Claude Code
Co-Authored-By: Claude <[email protected]>
EOF
)"
使用单引号的原因:<<'EOF' 可防止内容中的变量展开。若要展开变量,请使用 <<"EOF"。
常见错误:忘记在 $() 包装器两侧加引号
# ❌ Wrong: Newlines lost
git commit -m $(cat <<'EOF'
Line 1
Line 2
EOF
)
# ✅ Correct: Preserves newlines
git commit -m "$(cat <<'EOF'
Line 1
Line 2
EOF
)"
模式 4:捕获和处理输出
适用场景:需要先处理命令输出再使用
模式:使用 $() 进行命令替换
示例:获取当前分支名称
BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Current branch: $BRANCH"
示例:根据输出执行条件逻辑
if git diff --quiet; then
echo "No changes detected"
else
echo "Changes detected, running tests..."
npm test
fi
限制:输出超过 30,000 个字符时会被截断。对于大型输出:
# Limit output
npm test 2>&1 | head -100
# Or save to file
npm test > test-results.txt && tail -50 test-results.txt
模式 5:条件执行
适用场景:根据条件采取不同操作
模式:使用 && / || 测试命令
示例:仅在文件发生更改时运行测试
git diff --quiet || npm test
示例:根据文件是否存在运行不同命令
[ -f package-lock.json ] && npm ci || npm install
示例:多条件逻辑
if [ -f pnpm-lock.yaml ]; then
pnpm install
elif [ -f yarn.lock ]; then
yarn install
else
npm install
fi
钩子:高级自动化
钩子是在工具执行前后运行的 shell 命令或 Claude 提示词。它们是你的安全卫士、清理助手和自动化帮手。
PreToolUse:安全防护
用途:在工具执行前运行,可阻止或修改行为
退出代码:
0= 允许执行1= 使用通用错误阻止2= 使用自定义错误消息阻止(来自 stderr)
用例 1:阻止危险命令
文件:~/.claude/hooks/dangerous-command-guard.py
#!/usr/bin/env python3
import json
import sys
import re
# Read hook input from stdin
data = json.load(sys.stdin)
command = data.get('tool_input', {}).get('command', '')
# Dangerous patterns to block
DANGEROUS = [
r'rm\s+-rf\s+/', # Delete root
r'dd\s+if=', # Disk operations
r'mkfs\.', # Format filesystem
r':()\{.*\}:', # Fork bomb
r'sudo\s+rm', # Sudo delete
r'git\s+push.*--force.*main', # Force push to main
]
for pattern in DANGEROUS:
if re.search(pattern, command):
print(f"BLOCKED: Dangerous command pattern '{pattern}'", file=sys.stderr)
sys.exit(2)
# Allow execution
sys.exit(0)
设置配置:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/dangerous-command-guard.py"
}
]
}
]
}
}
用例 2:记录所有 Bash 命令
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo \"[$(date -Iseconds)] $(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.command')\" >> ~/.claude/bash-audit.log"
}
]
}
结果:每条 Bash 命令都会连同时间戳记录到 ~/.claude/bash-audit.log
用例 3:强制使用指定的包管理器
检查锁文件并阻止使用错误的包管理器:
#!/bin/bash
# File: ~/.claude/hooks/package-manager-enforcer.sh
COMMAND=$(echo "$CLAUDE_TOOL_INPUT" | jq -r '.tool_input.command')
if [ -f pnpm-lock.yaml ] && echo "$COMMAND" | grep -qE '^(npm|yarn) '; then
echo "ERROR: This repo uses pnpm. Please use 'pnpm' instead of 'npm' or 'yarn'." >&2
exit 2
fi
if [ -f yarn.lock ] && echo "$COMMAND" | grep -qE '^(npm|pnpm) '; then
echo "ERROR: This repo uses yarn. Please use 'yarn' instead of 'npm' or 'pnpm'." >&2
exit 2
fi
exit 0
PostToolUse:清理工作
用途:在工具成功执行后运行(仅退出代码为 0 时)
示例:编辑文件后自动格式化
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "FILE=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.file_path'); [ -f \"$FILE\" ] && prettier --write \"$FILE\" || true"
}
]
}
示例:代码变更后运行测试
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "FILE=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.file_path'); if echo \"$FILE\" | grep -qE '\\.(ts|tsx|js|jsx)$'; then npm test -- \"$FILE\"; fi"
}
]
}
SessionStart:环境设置
用途:在会话开始时运行一次,设置环境
示例:加载项目专属环境
{
"hooks": {
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "[ -f .envrc ] && source .envrc || true; env > $CLAUDE_ENV_FILE"
}
]
}
]
}
}
Hook 中可用的环境变量:
$CLAUDE_TOOL_INPUT- 工具调用的 JSON 字符串$CLAUDE_ENV_FILE- 环境文件的路径- 标准环境变量(
$HOME、$USER、$PWD等)
Git 工作流(经过生产环境验证)
Anthropic 的工程团队在 90% 以上的 Git 操作中使用了这些模式。
模式:智能 Git 提交
第 1 步:收集上下文(并行调用)
# Call 1
git status
# Call 2
git diff --staged
# Call 3
git log -5 --oneline
为何并行:操作彼此独立,响应更快,用户体验更好
第 2 步:分析变更
- 检查实际代码变更(不只是文件名!)
- 参照 Git 日志中的提交消息风格
- 关注“为什么”,而不是“是什么”
- 保持消息简洁(1-2 句话)
第 3 步:使用 HEREDOC 提交
git add [files] && git commit -m "$(cat <<'EOF'
feat(auth): Add JWT verification middleware
Implement custom JWT template support for Clerk auth.
Extracts email and metadata claims for user context.
🤖 Generated with Claude Code
Co-Authored-By: Claude <[email protected]>
EOF
)"
第 4 步:验证
git status
重要:如果预提交 Hook 修改了文件:
- 检查作者身份:
git log -1 --format='%an %ae' - 检查是否尚未推送:
git status(应显示 “ahead of origin”) - 如果两项都安全:
git add . && git commit --amend --no-edit - 如果不安全:
git add . && git commit -m "Apply pre-commit hook changes"
模式:创建拉取请求
第 1 步:了解分支状态(并行)
# Call 1
git status
# Call 2
git diff main...HEAD
# Call 3
git log main..HEAD --oneline
第 2 步:分析所有提交(不只是最新提交!)
- 自分支与 main 分叉以来有哪些变更?
- 此分支的总体目标是什么?
- 需要测试哪些内容?
第 3 步:使用 gh CLI 创建 PR
gh pr create --title "feat: User Authentication" --body "$(cat <<'EOF'
## Summary
- Implement JWT verification with Clerk
- Add login/logout endpoints
- Update database schema for users table
## Test Plan
- [ ] Verify JWT token validation
- [ ] Test login flow
- [ ] Test logout flow
- [ ] Confirm database migrations work
🤖 Generated with Claude Code
EOF
)"
结果:创建内容专业的 PR,包含清晰的摘要和测试计划
CLI 工具集成
GitHub CLI(gh)
Claude 默认了解 gh CLI。常见模式:
# View PR comments
gh api repos/owner/repo/pulls/123/comments
# Check CI status
gh run list --limit 5
# Create issue
gh issue create --title "Bug: Description" --body "Details here"
# Comment on PR
gh pr comment 123 --body "LGTM! 🚀"
Wrangler(Cloudflare)
本地安装时使用 npx 前缀:
# Deploy worker
npx wrangler deploy
# Run D1 migrations
npx wrangler d1 migrations apply my-db --remote
# Tail logs
npx wrangler tail
# Execute D1 query
npx wrangler d1 execute my-db --command "SELECT * FROM users LIMIT 5"
自定义 CLI 工具
如何让 Claude 了解你的 CLI:
选项 1:在 CLAUDE.md 中记录
## Custom Tools
**mycli**: Internal deployment tool
Usage: `mycli deploy --env production --service api`
Help: `mycli --help` for full options
Config: `.mycli.json` in project root
选项 2:让 Claude 自行探索
When encountering mycli commands, run `mycli --help` first to discover available options.
选项 3:创建自定义命令(.claude/commands/deploy.md)
Deploy using our internal mycli tool:
1. Run `mycli --version` to verify installation
2. Check current environment: `mycli env current`
3. Deploy to staging: `mycli deploy --env staging --service api`
4. Run smoke tests: `mycli test smoke --env staging`
5. If tests pass, deploy to production: `mycli deploy --env production --service api`
安全配置
1. 危险命令防护(PreToolUse Hook)
参见打包脚本:scripts/dangerous-command-guard.py
阻止:
rm -rf /(删除根目录)dd if=(磁盘操作)mkfs.*(格式化文件系统):(){ :|:& };:(Fork 炸弹)sudo rm(危险的 sudo 删除操作)git push --force main(强制推送到 main 分支)
安装:
# Copy script
cp scripts/dangerous-command-guard.py ~/.claude/hooks/
chmod +x ~/.claude/hooks/dangerous-command-guard.py
# Configure in ~/.claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/dangerous-command-guard.py"
}
]
}
]
}
}
2. 生产文件保护
防止修改生产环境配置文件:
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "FILE=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.file_path // empty'); if echo \"$FILE\" | grep -qE '(^|\\/)(production\\.env|\\.env\\.production|prod\\.config)$'; then echo 'ERROR: Cannot modify production config files' >&2; exit 2; fi"
}
]
}
3. 审计日志
记录所有 Bash 命令以满足合规要求:
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo \"[$(date -Iseconds)] User: $USER | Command: $(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.tool_input.command')\" >> ~/.claude/audit.log"
}
]
}
查看审计日志:
tail -50 ~/.claude/audit.log
自定义命令(.claude/commands/)
自定义命令是 Markdown 文件,调用时会展开为提示词。
创建自定义命令
文件:.claude/commands/deploy-staging.md
Deploy the current branch to staging environment:
1. Verify branch is not main (exit if main)
2. Run full test suite (npm test)
3. Build production bundle (npm run build)
4. Deploy with wrangler to staging (npx wrangler deploy --env staging)
5. Run smoke tests against staging URL
6. Share deployment URL with user
用法:
User: /deploy-staging
Claude: [Executes the workflow from the markdown file]
自定义命令最佳实践
✅ 应该:
- 保持原子性(一个明确的工作流)
- 包含验证步骤
- 记录预期状态
- 添加回滚说明
- 使用祈使语气
❌ 不应该:
- 让命令过于复杂(拆分成多个命令)
- 包含交互式提示
- 假设状态已就绪(始终进行验证)
命令库示例:
/deploy-staging- 部署到预发布环境/deploy-production- 部署到生产环境(包含安全检查)/run-tests- 运行完整测试套件/check-types- 执行 TypeScript 类型检查/format-code- 格式化所有代码文件/create-migration- 创建数据库迁移
关键规则
始终做到 ✅
1. 优先使用专用工具
Bash 功能强大,但对于有专用工具的任务来说效率较低:
# ❌ Wrong: Use Bash for file reading
cat file.txt
# ✅ Correct: Use Read tool
Read(file_path="file.txt")
# ❌ Wrong: Use Bash for file search
find . -name "*.ts"
# ✅ Correct: Use Glob tool
Glob(pattern="**/*.ts")
# ❌ Wrong: Use Bash for content search
grep "pattern" file.txt
# ✅ Correct: Use Grep tool
Grep(pattern="pattern", path="file.txt")
原因:专用工具速度更快、占用的令牌更少,而且格式更好。
2. 为包含空格的路径加引号
# ❌ Wrong: Breaks on spaces
cd /Users/name/My Documents
# ✅ Correct: Quoted path
cd "/Users/name/My Documents"
3. 使用 && 处理依赖关系
# ❌ Wrong: Continues even if install fails
npm install ; npm run build
# ✅ Correct: Stops on failure
npm install && npm run build
4. 并行执行互不依赖的操作
# ❌ Wrong: Sequential when could be parallel
git status && git diff && git log
# ✅ Correct: Make 3 parallel Bash tool calls in one message
5. 多行字符串使用 HEREDOC
# ❌ Wrong: Escaping nightmare
git commit -m "line1\nline2\nline3"
# ✅ Correct: HEREDOC
git commit -m "$(cat <<'EOF'
line1
line2
line3
EOF
)"
6. 始终提供描述
# ❌ Wrong: No context for user
Bash(command="complex-script.sh")
# ✅ Correct: Clear purpose
Bash(
command="complex-script.sh",
description="Run integration tests on staging database"
)
绝不这样做 ❌
1. 不要使用交互式命令
需要用户输入的命令会一直挂起:
# ❌ Wrong: Will hang waiting for input
vim file.txt
nano file.txt
less output.txt
npm install # If package.json has prompts
# ✅ Correct: Use non-interactive alternatives
# Use Edit/Write tools for file editing
npm install --yes
2. 不要用换行符串联命令
# ❌ Wrong: Doesn't work as expected
command1
command2
# ✅ Correct: Use && or ;
command1 && command2
3. 不要忽略退出代码
# ❌ Wrong: Success message even if command failed
risky-command ; echo "Success!"
# ✅ Correct: Check exit code
risky-command && echo "Success!" || echo "Failed!"
4. 不要过度使用 cd
在 Agent 模式下,工作目录不会在调用之间保留:
# ❌ Wrong: cd doesn't persist
# Call 1: cd /path/to/project
# Call 2: npm test # Runs in original directory!
# ✅ Correct: Use absolute paths or --prefix
npm test --prefix /path/to/project
# ✅ Or chain in single command
cd /path/to/project && npm test
5. 不要跳过错误处理
# ❌ Wrong: No error handling
./script.sh
./cleanup.sh
# ✅ Correct: Handle failures
./script.sh || { echo "Script failed" >&2; exit 1; }
./cleanup.sh
防止已知问题
此技能可防止 12 个有记录的问题,相关来源如下:
问题 #1:Git Bash 中找不到 cygpath 命令(Windows)
错误:bash: line 1: cygpath: command not found
来源:https://github.com/anthropics/claude-code/issues/9883
原因:Bash 工具在 MSYS/Git Bash 中尝试使用仅适用于 Cygwin 的 cygpath
预防方法:
- 在 Windows 上使用 WSL,而不是 Git Bash
- 如果使用 Git Bash,请配置
CLAUDE_CODE_GIT_BASH_PATH - 如果需要 cygpath,请安装 Cygwin
问题 #2:管道命令失败
错误:echo test|grep test 返回错误,而不是“test”
来源:https://github.com/anthropics/claude-code/issues/774
原因:某些配置中的管道解析问题
预防方法:
# ❌ Avoid direct pipes
echo test|grep test
# ✅ Use explicit bash -c
bash -c 'echo test | grep test'
# ✅ Or use specialized tools (Grep tool instead)
问题 #3:命令超时(挂起的 Promise)
错误:A hanging Promise was canceled
来源:Bash 工具的默认超时时间为 2 分钟
原因:长时间运行的命令未配置超时时间
预防方法:
# For long operations, set timeout explicitly
Bash(
command="npm run build",
timeout=600000, # 10 minutes
description="Build production bundle (may take several minutes)"
)
# Or run in background
Bash(
command="npm run build > build.log 2>&1 &",
description="Start build in background"
)
问题 #4:输出截断导致内容丢失
错误:响应中缺少重要输出 来源:Bash 工具会在 30,000 个字符处截断输出 原因:大型命令输出超出限制
预防方法:
# ❌ Wrong: Full output may be truncated
npm test
# ✅ Correct: Limit output
npm test 2>&1 | head -100
# ✅ Or save to file
npm test > test-results.txt && tail -50 test-results.txt
问题 #5:“未找到合适的 Shell”(Windows)
错误:CLI 报错“未找到合适的 Shell” 来源:https://github.com/anthropics/claude-code/issues/3461 原因:Git Bash 环境中的 Shell 检测问题
预防方法:
- 显式设置 SHELL 环境变量
- 使用 WSL 以获得更好的兼容性
- 安装最新版本的 Claude Code CLI
问题 #6:无法使用 Bash 工具
错误:Claude 失去运行 Bash() 工具的能力 来源:https://github.com/anthropics/claude-code/issues/1888 原因:会话状态损坏,通常发生在闲置一夜之后
预防方法:
- 如果 Bash 无法使用,请重启 Claude Code 会话
- 使用
/permissions命令检查权限 - 使用
restart: true参数重置 bash 会话
问题 #7:交互式提示导致挂起
错误:命令无限期挂起,没有输出 原因:命令需要交互式输入(密码、确认)
预防方法:
# ❌ Wrong: Will hang
npm install # If package.json has interactive prompts
# ✅ Correct: Non-interactive flags
npm install --yes
# ✅ Correct: Provide input via stdin
echo "yes" | command-that-needs-confirmation
问题 #8:权限被拒绝错误
错误:permission denied 或 command not found
原因:脚本不可执行或不在 PATH 中
预防方法:
# Make script executable first
chmod +x script.sh && ./script.sh
# Use full path
/usr/local/bin/mycli deploy
# Or use interpreter directly
python3 script.py
node script.js
问题 #9:环境变量未持久化
错误:在一条命令中设置的变量在下一条命令中不可用 原因:Agent 线程会在调用之间重置环境
预防措施:
# ❌ Wrong: Split across calls
# Call 1: export API_KEY=abc123
# Call 2: curl -H "Authorization: $API_KEY" ... # $API_KEY empty!
# ✅ Correct: Same command
export API_KEY=abc123 && curl -H "Authorization: $API_KEY" ...
# ✅ Or use SessionStart hook
问题 #10:未检测到 Git 提交钩子的修改
错误:提交前钩子修改了文件,但提交失败 原因:钩子在暂存后修改文件
预防措施:
# After commit fails due to hook changes:
# 1. Check if you can amend (not pushed, authored by you)
git log -1 --format='%an %ae'
# 2. If safe, amend
git add . && git commit --amend --no-edit
# 3. If not safe, make new commit
git add . && git commit -m "Apply pre-commit hook changes"
问题 #11:通配符权限匹配不起作用
错误:Bash(*) 或 Bash(*:*) 无法授予访问权限
来源:https://github.com/anthropics/claude-code/issues/462
原因:允许列表中的语法不匹配
预防措施:
// ❌ Wrong
{"allowedTools": ["Bash(*)"]}
// ✅ Correct
{"allowedTools": ["Bash"]}
// Or specific patterns
{"allowedTools": ["Bash(git *)", "Bash(npm *)"]}
问题 #12:执行危险命令
错误:意外执行 rm -rf / 或强制推送到 main
原因:破坏性操作没有防护措施
预防措施:使用 PreToolUse 钩子拦截危险命令(参见“安全”部分)
使用捆绑资源
脚本(scripts/)
1. dangerous-command-guard.py 用途:用于拦截危险 Bash 模式的 PreToolUse 钩子 用法:在 settings.json 中配置(参见“安全”部分)
2. bash-audit-logger.sh 用途:记录所有 Bash 命令及其时间戳 用法:配置为 PreToolUse 钩子
3. package-manager-enforcer.sh 用途:根据锁文件强制使用 pnpm/yarn/npm 用法:配置为 PreToolUse 钩子
参考资料(references/)
1. git-workflows.md 深入介绍 Git 自动化模式、提交消息格式和 PR 创建
2. hooks-examples.md 针对常见场景的完整钩子配置示例
3. cli-tool-integration.md 如何将自定义 CLI 工具与 Claude Code 集成
4. security-best-practices.md Bash 自动化的综合安全指南
5. troubleshooting-guide.md 针对所有 12 个已知问题的详细解决方案
模板(templates/)
1. settings.json 包含钩子示例的完整 settings.json
2. dangerous-commands.json 需要拦截的危险模式列表
3. custom-command-template.md 用于创建 .claude/commands/ 文件的模板
4. github-workflow.yml 将 GitHub Actions 与 Claude Code 集成
5. .envrc.example 使用 direnv 管理环境的集成示例
依赖项
必需:
- Claude Code CLI(最新版本)
- bash 4.0+(支持持久会话)
可选(用于特定功能):
jq(在钩子中处理 JSON)-brew install jq/apt install jqgh(GitHub CLI 集成)-brew install gh/apt install gh- Python 3.7+(用于基于 Python 的钩子)
- direnv(环境管理)-
brew install direnv
官方文档
- Bash 工具参考:https://docs.claude.com/en/docs/claude-code/tools
- Claude Code 钩子:https://docs.claude.com/en/docs/claude-code/hooks
- Claude Code 最佳实践:https://www.anthropic.com/engineering/claude-code-best-practices
- 使用 MCP 执行代码:https://www.anthropic.com/engineering/code-execution-with-mcp
- Cloudflare Code Mode:https://blog.cloudflare.com/code-mode/
生产环境示例
此技能基于以下项目中的实际使用经验:
- WordPress Auditor:Git 工作流、PR 自动化
- claude-skills repo:自定义命令、钩子配置
- 多个客户端项目:CLI 工具编排
实测效果:
- Token 节省:约 55%(相较于手动试错)
- 错误预防:记录在案的 12 个问题 → 0 次发生
- 时间节省:借助并行执行,工作流提速约 40%
- 安全性:通过钩子 100% 拦截危险命令
完整设置清单
- 已安装并更新 Claude Code CLI
- 已安装 Bash 4.0+(
bash --version) - 已安装 jq(用于钩子):
brew install jq或apt install jq - 已安装 gh CLI(用于 Git 工作流):
brew install gh或apt install gh - 已创建设置目录:
mkdir -p ~/.claude/hooks - 已将钩子脚本复制到
~/.claude/hooks/ - 已将脚本设为可执行:
chmod +x ~/.claude/hooks/*.sh - 已在
~/.claude/settings.json中配置所需的钩子 - 已测试危险命令防护
- 已验证 Bash 审计日志记录
- 已在
.claude/commands/中创建第一个自定义命令 - 已测试 Git 工作流模式
有问题?
- 查看
references/troubleshooting-guide.md,获取详细解决方案 - 查看
references/hooks-examples.md,了解配置示例 - 查阅官方文档:https://docs.claude.com/en/docs/claude-code/hooks
- 确认已完成上述设置清单中的所有步骤