claude-code-bash-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code Bash Patterns

Claude Code Bash 使用模式

Status: Production Ready ✅ | Last Verified: 2025-11-18

状态:已就绪可用于生产环境 ✅ | 最后验证时间:2025-11-18

Quick Start

快速开始

Basic Command

基础命令

bash
ls -la
bash
ls -la

Command Chaining

命令链式调用

bash
bun install && bun run build && bun test
bash
bun install && bun run build && bun test

Hooks

钩子

Create
.claude-hook-pretooluse.sh
:
bash
#!/usr/bin/env bash
创建
.claude-hook-pretooluse.sh
bash
#!/usr/bin/env bash

PreToolUse 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 push
Why: 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 parallel
Load
references/cli-tool-integration.md
for parallel patterns.

适用场景:命令之间相互独立
包含多个并行Bash工具调用的消息
加载
references/cli-tool-integration.md
查看并行执行模式。

3. Session Persistence

3. 会话状态持久化

Use when: Need to maintain state across commands
bash
undefined
适用场景:需要跨命令维护状态
bash
undefined

Set 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
references/hooks-examples.md
for all hook types.

适用场景:需要命令执行前后的逻辑处理
加载
references/hooks-examples.md
查看所有钩子类型。

Critical Rules

关键规则

Always Do ✅

务必遵循 ✅

  1. Use && for sequential dependencies (not semicolons)
  2. Quote paths with spaces (
    cd "path with spaces"
    )
  3. Check environment before destructive ops (rm, git push --force)
  4. Use specialized tools first (Read, Grep, Glob before Bash)
  5. Set timeouts for long operations (up to 10 minutes)
  6. Validate inputs before passing to shell commands
  7. Use hooks for repeated patterns (logging, validation)
  8. Maintain session state (export variables once)
  9. Handle errors explicitly (check exit codes)
  10. Document custom commands in .claude/commands/
  1. 使用 && 处理依赖顺序执行(而非分号)
  2. 为含空格的路径添加引号
    cd "path with spaces"
  3. 执行破坏性操作前检查环境(如rm、git push --force)
  4. 优先使用专用工具(优先用Read、Grep、Glob而非Bash)
  5. 为长时间操作设置超时(最长10分钟)
  6. 传递参数到Shell命令前先验证输入
  7. 使用钩子处理重复模式(如日志、验证)
  8. 维护会话状态(仅导出一次变量)
  9. 显式处理错误(检查退出码)
  10. 在 .claude/commands/ 中记录自定义命令

Never Do ❌

切勿执行 ❌

  1. Never use ; for dependent commands (use &&)
  2. Never skip quoting paths with spaces
  3. Never run rm -rf without confirmation
  4. Never expose secrets in command output
  5. Never ignore timeout limits (max 10 min)
  6. Never use bash for file operations when specialized tools exist
  7. Never chain with newlines (use && or ; explicitly)
  8. Never force-push to main without explicit user request
  9. Never skip hooks (--no-verify) without user request
  10. Never use interactive commands (git rebase -i, git add -i)

  1. 切勿使用分号处理依赖命令(改用&&)
  2. 切勿不为含空格的路径添加引号
  3. 切勿未经确认就执行 rm -rf
  4. 切勿在命令输出中暴露敏感信息
  5. 切勿忽略超时限制(最长10分钟)
  6. 当有专用工具时,切勿用Bash处理文件操作
  7. 切勿用换行符连接命令(显式使用&&或;)
  8. 切勿未经用户明确请求就强制推送到主分支
  9. 切勿未经用户请求就跳过钩子(--no-verify)
  10. 切勿使用交互式命令(如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 push
bash
npm test && git add . && git commit -m "fix: bug fix" && git push

Pull Request

拉取请求

bash
git checkout -b feature/new && git add . && git commit -m "feat: new feature" && git push -u origin feature/new
Load
references/git-workflows.md
for complete workflows including:
  • 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.sh
:
bash
#!/usr/bin/env bash
COMMAND="$1"
.claude-hook-pretooluse.sh
bash
#!/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
undefined
if [[ "$COMMAND" =~ rm\ -rf\ / ]]; then echo "❌ 已拦截危险命令" exit 1 fi
undefined

Hook Types

钩子类型

  • pretooluse - Before every Bash command
  • stop - Before conversation ends
  • user-prompt-submit - After user submits message
Load
references/hooks-examples.md
for all hook types and examples.

  • pretooluse - 在每个Bash命令执行前运行
  • stop - 在对话结束前运行
  • user-prompt-submit - 用户提交消息后运行
加载
references/hooks-examples.md
查看所有钩子类型及示例。

CLI Tool Integration

CLI工具集成

npm/bun

npm/bun

bash
bun install && bun run build
bash
bun install && bun run build

wrangler (Cloudflare)

wrangler(Cloudflare)

bash
bunx wrangler deploy
bash
bunx wrangler deploy

gh (GitHub CLI)

gh(GitHub CLI)

bash
gh pr create --title "Fix bug" --body "Description"
Load
references/cli-tool-integration.md
for complete tool patterns.

bash
gh pr create --title "Fix bug" --body "Description"
加载
references/cli-tool-integration.md
查看完整的工具模式。

Custom Commands

自定义命令

Create
.claude/commands/deploy.md
:
markdown
---
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:
/deploy
Load
templates/custom-command-template.md
for template.

创建
.claude/commands/deploy.md
markdown
---
description: Deploy to production
---

执行以下步骤:
1. 运行测试:`npm test`
2. 构建项目:`npm run build`
3. 部署:`wrangler deploy`
用户可通过
/deploy
调用该命令。
加载
templates/custom-command-template.md
查看模板。

Security

安全防护

Allowlisting Tools

工具白名单

settings.json
:
json
{
  "dangerousCommandsAllowList": [
    "git push --force"
  ]
}
settings.json
json
{
  "dangerousCommandsAllowList": [
    "git push --force"
  ]
}

Secrets Management

敏感信息管理

bash
undefined
bash
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 deploy
bash
npm run lint && npm test && npm run build && bunx wrangler deploy

Use Case 3: Multi-Repo Operations

场景3:多仓库操作

bash
cd repo1 && git pull && cd ../repo2 && git pull
bash
cd repo1 && git pull && cd ../repo2 && git pull

Use Case 4: Background Process

场景4:后台进程

bash
npm run dev &
Load
references/cli-tool-integration.md
for more patterns.

bash
npm run dev &
加载
references/cli-tool-integration.md
查看更多模式。

Troubleshooting

故障排查

Issue: Command times out

问题:命令超时

Solution: Increase timeout or use background mode
bash
undefined
解决方案:增加超时时间或使用后台模式
bash
undefined

Background mode

后台模式

npm run dev &
undefined
npm run dev &
undefined

Issue: 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.sh
Load
references/troubleshooting-guide.md
for all issues.

解决方案:检查
.claude-hook-pretooluse.sh
中的钩子逻辑
加载
references/troubleshooting-guide.md
查看所有问题及解决方案。

When to Load References

何时加载参考文档

Load
references/git-workflows.md
when:

当以下情况时加载
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

  • Creating custom hooks
  • Need hook templates
  • Want validation patterns
  • Implementing logging/security
  • 创建自定义钩子
  • 需要钩子模板
  • 查找验证模式
  • 实现日志/安全防护

Load
references/cli-tool-integration.md
when:

当以下情况时加载
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

  • Configuring security guards
  • Setting up allowlisting
  • Managing secrets
  • Preventing dangerous operations
  • 配置安全防护
  • 设置白名单
  • 管理敏感信息
  • 阻止危险操作

Load
references/troubleshooting-guide.md
when:

当以下情况时加载
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/oauth
bash
git checkout -b feature/oauth && \
  npm test && \
  git add . && \
  git commit -m "feat(auth): add OAuth support" && \
  git push -u origin feature/oauth

CI/CD Pipeline

CI/CD流水线

bash
npm run lint && \
  npm test && \
  npm run build && \
  bunx wrangler deploy
bash
npm run lint && \
  npm test && \
  npm run build && \
  bunx wrangler deploy

Multi-Project Update

多项目更新

bash
cd project1 && bun install && cd ../project2 && bun install

bash
cd project1 && bun install && cd ../project2 && bun install

Official Documentation

官方文档


Questions? Issues?
  1. Check
    references/troubleshooting-guide.md
    for common issues
  2. Review
    references/git-workflows.md
    for git patterns
  3. See
    references/hooks-examples.md
    for automation
  4. Load
    references/security-best-practices.md
    for security

有疑问或问题?
  1. 查看
    references/troubleshooting-guide.md
    了解常见问题
  2. 查看
    references/git-workflows.md
    了解Git模式
  3. 查看
    references/hooks-examples.md
    了解自动化方案
  4. 查看
    references/security-best-practices.md
    了解安全防护