claude-code-bash-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Code Bash Patterns
Claude Code Bash 使用模式
Status: Production Ready ✅ | Last Verified: 2025-11-18
状态:已就绪可用于生产环境 ✅ | 最后验证时间:2025-11-18
Quick Start
快速开始
Basic Command
基础命令
bash
ls -labash
ls -laCommand Chaining
命令链式调用
bash
bun install && bun run build && bun testbash
bun install && bun run build && bun testHooks
钩子
Create :
.claude-hook-pretooluse.shbash
#!/usr/bin/env bash创建 :
.claude-hook-pretooluse.shbash
#!/usr/bin/env bashPreToolUse hook - runs before every Bash command
PreToolUse 钩子 - 在每个Bash命令执行前运行
echo "Running: $1"
**Load `references/hooks-examples.md` for complete hook patterns.**
---echo "Running: $1"
**加载 `references/hooks-examples.md` 查看完整的钩子模式。**
---The Five Core Patterns
五大核心模式
1. Sequential Operations (&&)
1. 顺序执行(&&)
Use when: Each command depends on previous success
bash
git add . && git commit -m "message" && git pushWhy: Stops chain if any command fails
适用场景:每个命令依赖前序命令执行成功
bash
git add . && git commit -m "message" && git push原因:如果任一命令执行失败,链式调用会终止
2. Parallel Operations (Multiple tool calls)
2. 并行执行(多工具调用)
Use when: Commands are independent
Message with multiple Bash tool calls in parallelLoad for parallel patterns.
references/cli-tool-integration.md适用场景:命令之间相互独立
包含多个并行Bash工具调用的消息加载 查看并行执行模式。
references/cli-tool-integration.md3. Session Persistence
3. 会话状态持久化
Use when: Need to maintain state across commands
bash
undefined适用场景:需要跨命令维护状态
bash
undefinedSet environment variable
设置环境变量
export API_KEY="sk-..."
export API_KEY="sk-..."
Use in later commands (same session)
在后续命令中使用(同一会话)
curl -H "Authorization: Bearer $API_KEY" api.example.com
---curl -H "Authorization: Bearer $API_KEY" api.example.com
---4. Background Processes
4. 后台进程
Use when: Long-running tasks
bash
npm run dev &适用场景:处理长时间运行的任务
bash
npm run dev &Get PID with $!
通过 $! 获取进程ID
---
---5. Hooks for Automation
5. 钩子自动化
Use when: Need pre/post command logic
Load for all hook types.
references/hooks-examples.md适用场景:需要命令执行前后的逻辑处理
加载 查看所有钩子类型。
references/hooks-examples.mdCritical Rules
关键规则
Always Do ✅
务必遵循 ✅
- Use && for sequential dependencies (not semicolons)
- Quote paths with spaces ()
cd "path with spaces" - Check environment before destructive ops (rm, git push --force)
- Use specialized tools first (Read, Grep, Glob before Bash)
- Set timeouts for long operations (up to 10 minutes)
- Validate inputs before passing to shell commands
- Use hooks for repeated patterns (logging, validation)
- Maintain session state (export variables once)
- Handle errors explicitly (check exit codes)
- Document custom commands in .claude/commands/
- 使用 && 处理依赖顺序执行(而非分号)
- 为含空格的路径添加引号()
cd "path with spaces" - 执行破坏性操作前检查环境(如rm、git push --force)
- 优先使用专用工具(优先用Read、Grep、Glob而非Bash)
- 为长时间操作设置超时(最长10分钟)
- 传递参数到Shell命令前先验证输入
- 使用钩子处理重复模式(如日志、验证)
- 维护会话状态(仅导出一次变量)
- 显式处理错误(检查退出码)
- 在 .claude/commands/ 中记录自定义命令
Never Do ❌
切勿执行 ❌
- Never use ; for dependent commands (use &&)
- Never skip quoting paths with spaces
- Never run rm -rf without confirmation
- Never expose secrets in command output
- Never ignore timeout limits (max 10 min)
- Never use bash for file operations when specialized tools exist
- Never chain with newlines (use && or ; explicitly)
- Never force-push to main without explicit user request
- Never skip hooks (--no-verify) without user request
- Never use interactive commands (git rebase -i, git add -i)
- 切勿使用分号处理依赖命令(改用&&)
- 切勿不为含空格的路径添加引号
- 切勿未经确认就执行 rm -rf
- 切勿在命令输出中暴露敏感信息
- 切勿忽略超时限制(最长10分钟)
- 当有专用工具时,切勿用Bash处理文件操作
- 切勿用换行符连接命令(显式使用&&或;)
- 切勿未经用户明确请求就强制推送到主分支
- 切勿未经用户请求就跳过钩子(--no-verify)
- 切勿使用交互式命令(如git rebase -i、git add -i)
Git Workflows
Git工作流
Basic Commit
基础提交
bash
git add . && git commit -m "feat: add feature"bash
git add . && git commit -m "feat: add feature"Commit with Testing
带测试的提交
bash
npm test && git add . && git commit -m "fix: bug fix" && git pushbash
npm test && git add . && git commit -m "fix: bug fix" && git pushPull Request
拉取请求
bash
git checkout -b feature/new && git add . && git commit -m "feat: new feature" && git push -u origin feature/newLoad for complete workflows including:
references/git-workflows.md- Feature branch workflow
- PR creation automation
- Commit message conventions
- Pre-commit validation
bash
git checkout -b feature/new && git add . && git commit -m "feat: new feature" && git push -u origin feature/new加载 查看完整工作流,包括:
references/git-workflows.md- 功能分支工作流
- PR创建自动化
- 提交消息规范
- 提交前验证
Hooks: Advanced Automation
钩子:高级自动化
PreToolUse Hook
PreToolUse钩子
.claude-hook-pretooluse.shbash
#!/usr/bin/env bash
COMMAND="$1".claude-hook-pretooluse.shbash
#!/usr/bin/env bash
COMMAND="$1"Log all commands
记录所有命令
echo "[$(date)] Running: $COMMAND" >> ~/claude-commands.log
echo "[$(date)] Running: $COMMAND" >> ~/claude-commands.log
Block dangerous patterns
拦截危险命令模式
if [[ "$COMMAND" =~ rm\ -rf\ / ]]; then
echo "❌ Blocked dangerous command"
exit 1
fi
undefinedif [[ "$COMMAND" =~ rm\ -rf\ / ]]; then
echo "❌ 已拦截危险命令"
exit 1
fi
undefinedHook Types
钩子类型
- pretooluse - Before every Bash command
- stop - Before conversation ends
- user-prompt-submit - After user submits message
Load for all hook types and examples.
references/hooks-examples.md- pretooluse - 在每个Bash命令执行前运行
- stop - 在对话结束前运行
- user-prompt-submit - 用户提交消息后运行
加载 查看所有钩子类型及示例。
references/hooks-examples.mdCLI Tool Integration
CLI工具集成
npm/bun
npm/bun
bash
bun install && bun run buildbash
bun install && bun run buildwrangler (Cloudflare)
wrangler(Cloudflare)
bash
bunx wrangler deploybash
bunx wrangler deploygh (GitHub CLI)
gh(GitHub CLI)
bash
gh pr create --title "Fix bug" --body "Description"Load for complete tool patterns.
references/cli-tool-integration.mdbash
gh pr create --title "Fix bug" --body "Description"加载 查看完整的工具模式。
references/cli-tool-integration.mdCustom Commands
自定义命令
Create :
.claude/commands/deploy.mdmarkdown
---
description: Deploy to production
---
Run these steps:
1. Run tests: `npm test`
2. Build: `npm run build`
3. Deploy: `wrangler deploy`User can invoke with:
/deployLoad for template.
templates/custom-command-template.md创建 :
.claude/commands/deploy.mdmarkdown
---
description: Deploy to production
---
执行以下步骤:
1. 运行测试:`npm test`
2. 构建项目:`npm run build`
3. 部署:`wrangler deploy`用户可通过 调用该命令。
/deploy加载 查看模板。
templates/custom-command-template.mdSecurity
安全防护
Allowlisting Tools
工具白名单
settings.jsonjson
{
"dangerousCommandsAllowList": [
"git push --force"
]
}settings.jsonjson
{
"dangerousCommandsAllowList": [
"git push --force"
]
}Secrets Management
敏感信息管理
bash
undefinedbash
undefined✅ Good: Use environment variables
✅ 推荐:使用环境变量
export API_KEY="$SECURE_VALUE"
export API_KEY="$SECURE_VALUE"
❌ Bad: Hardcode secrets
❌ 不推荐:硬编码敏感信息
curl -H "Authorization: Bearer sk-abc123..."
**Load `references/security-best-practices.md` for complete security guide.**
---curl -H "Authorization: Bearer sk-abc123..."
**加载 `references/security-best-practices.md` 查看完整的安全指南。**
---Common Use Cases
常见使用场景
Use Case 1: Test Before Commit
场景1:提交前测试
bash
npm test && git add . && git commit -m "message"bash
npm test && git add . && git commit -m "message"Use Case 2: Deploy with Validation
场景2:带验证的部署
bash
npm run lint && npm test && npm run build && bunx wrangler deploybash
npm run lint && npm test && npm run build && bunx wrangler deployUse Case 3: Multi-Repo Operations
场景3:多仓库操作
bash
cd repo1 && git pull && cd ../repo2 && git pullbash
cd repo1 && git pull && cd ../repo2 && git pullUse Case 4: Background Process
场景4:后台进程
bash
npm run dev &Load for more patterns.
references/cli-tool-integration.mdbash
npm run dev &加载 查看更多模式。
references/cli-tool-integration.mdTroubleshooting
故障排查
Issue: Command times out
问题:命令超时
Solution: Increase timeout or use background mode
bash
undefined解决方案:增加超时时间或使用后台模式
bash
undefinedBackground mode
后台模式
npm run dev &
undefinednpm run dev &
undefinedIssue: Path with spaces fails
问题:含空格的路径执行失败
Solution: Quote the path
bash
cd "path with spaces/file.txt"解决方案:为路径添加引号
bash
cd "path with spaces/file.txt"Issue: Hook blocks command
问题:钩子拦截命令
Solution: Check hook logic in
.claude-hook-pretooluse.shLoad for all issues.
references/troubleshooting-guide.md解决方案:检查 中的钩子逻辑
.claude-hook-pretooluse.sh加载 查看所有问题及解决方案。
references/troubleshooting-guide.mdWhen to Load References
何时加载参考文档
Load references/git-workflows.md
when:
references/git-workflows.md当以下情况时加载 references/git-workflows.md
:
references/git-workflows.md- Setting up git automation
- Creating PRs programmatically
- Need commit message conventions
- Want pre-commit validation patterns
- 配置Git自动化
- 程序化创建PR
- 需要提交消息规范
- 查找提交前验证模式
Load references/hooks-examples.md
when:
references/hooks-examples.md当以下情况时加载 references/hooks-examples.md
:
references/hooks-examples.md- Creating custom hooks
- Need hook templates
- Want validation patterns
- Implementing logging/security
- 创建自定义钩子
- 需要钩子模板
- 查找验证模式
- 实现日志/安全防护
Load references/cli-tool-integration.md
when:
references/cli-tool-integration.md当以下情况时加载 references/cli-tool-integration.md
:
references/cli-tool-integration.md- Orchestrating multiple CLI tools
- Need tool-specific patterns
- Want parallel execution examples
- Troubleshooting tool integration
- 编排多个CLI工具
- 需要工具特定模式
- 查找并行执行示例
- 排查工具集成问题
Load references/security-best-practices.md
when:
references/security-best-practices.md当以下情况时加载 references/security-best-practices.md
:
references/security-best-practices.md- Configuring security guards
- Setting up allowlisting
- Managing secrets
- Preventing dangerous operations
- 配置安全防护
- 设置白名单
- 管理敏感信息
- 阻止危险操作
Load references/troubleshooting-guide.md
when:
references/troubleshooting-guide.md当以下情况时加载 references/troubleshooting-guide.md
:
references/troubleshooting-guide.md- Debugging command failures
- Encountering timeouts
- Hooks behaving unexpectedly
- Session state issues
- 调试命令执行失败
- 遇到超时问题
- 钩子行为异常
- 会话状态异常
Using Bundled Resources
使用内置资源
References (references/)
参考文档(references/)
- git-workflows.md - Complete git automation patterns
- hooks-examples.md - All hook types with examples
- cli-tool-integration.md - Tool orchestration patterns
- security-best-practices.md - Security configuration guide
- troubleshooting-guide.md - Common issues and solutions
- git-workflows.md - 完整的Git自动化模式
- hooks-examples.md - 所有钩子类型及示例
- cli-tool-integration.md - 工具编排模式
- security-best-practices.md - 安全配置指南
- troubleshooting-guide.md - 常见问题及解决方案
Templates (templates/)
模板(templates/)
- custom-command-template.md - Custom command template
- settings.json - Security settings example
- .envrc.example - Environment variables example
- github-workflow.yml - GitHub Actions integration
- dangerous-commands.json - Dangerous patterns list
- custom-command-template.md - 自定义命令模板
- settings.json - 安全配置示例
- .envrc.example - 环境变量示例
- github-workflow.yml - GitHub Actions集成示例
- dangerous-commands.json - 危险命令模式列表
Examples
示例
Feature Development Workflow
功能开发工作流
bash
git checkout -b feature/oauth && \
npm test && \
git add . && \
git commit -m "feat(auth): add OAuth support" && \
git push -u origin feature/oauthbash
git checkout -b feature/oauth && \
npm test && \
git add . && \
git commit -m "feat(auth): add OAuth support" && \
git push -u origin feature/oauthCI/CD Pipeline
CI/CD流水线
bash
npm run lint && \
npm test && \
npm run build && \
bunx wrangler deploybash
npm run lint && \
npm test && \
npm run build && \
bunx wrangler deployMulti-Project Update
多项目更新
bash
cd project1 && bun install && cd ../project2 && bun installbash
cd project1 && bun install && cd ../project2 && bun installOfficial Documentation
官方文档
- Claude Code Bash Tool: https://docs.claude.com/en/docs/claude-code/tools
- Hooks: https://docs.claude.com/en/docs/claude-code/hooks
- Custom Commands: https://docs.claude.com/en/docs/claude-code/custom-commands
Questions? Issues?
- Check for common issues
references/troubleshooting-guide.md - Review for git patterns
references/git-workflows.md - See for automation
references/hooks-examples.md - Load for security
references/security-best-practices.md
- Claude Code Bash Tool: https://docs.claude.com/en/docs/claude-code/tools
- Hooks: https://docs.claude.com/en/docs/claude-code/hooks
- Custom Commands: https://docs.claude.com/en/docs/claude-code/custom-commands
有疑问或问题?
- 查看 了解常见问题
references/troubleshooting-guide.md - 查看 了解Git模式
references/git-workflows.md - 查看 了解自动化方案
references/hooks-examples.md - 查看 了解安全防护
references/security-best-practices.md