Home About Me

Working Effectively with Claude Code: A Practical Guide from First Run to Advanced Automation

Claude Code stands out in the crowded field of AI coding tools because it does more than generate snippets. Its real strength comes from three things working together: strong coding ability, a terminal-first interaction model, and tight integration with real development workflows. Used well, it can help with everything from writing code and fixing bugs to managing projects and automating repeatable engineering tasks.

What makes it valuable is not just raw model capability, but how naturally it fits into day-to-day software work. You can use it in the terminal, connect it to your IDE, define project rules, resume interrupted sessions, build reusable commands, monitor cost, and even connect it to external systems or GitHub automation.

Getting started: the basics that unlock the rest

Claude Code runs primarily in the terminal, but it also works well alongside mainstream IDEs. Learning the basic commands and configuration model is the fastest way to make it genuinely useful.

IDE extensions: combine terminal flexibility with editor convenience

Because Claude Code is native to the terminal, editing files and previewing code there is not always as comfortable as working inside an IDE. Official extensions are available for common tools such as VS Code, Cursor, and JetBrains IDEs. Once installed, they let you start sessions, inspect code, and run Claude Code commands from within your editor while keeping the power of terminal-based workflows.

Setup is simple: search for Claude Code in your IDE’s extension marketplace, install it, restart the IDE, and then use the integrated terminal to run Claude Code normally.

Core commands worth memorizing

The command-line interface centers on the claude command, with flags and subcommands for different styles of work. These are the ones you are most likely to use regularly:

<table> <thead> <tr> <th>Command</th> <th>Main purpose</th> <th>Example</th> <th>Best for</th> </tr> </thead> <tbody> <tr> <td>claude</td> <td>Start an interactive session</td> <td>claude</td> <td>Ongoing development tasks such as coding, refactoring, and debugging</td> </tr> <tr> <td>claude "task"</td> <td>Run a one-off task</td> <td>claude "fix the build error in App.vue"</td> <td>Simple single tasks that do not need a lasting session</td> </tr> <tr> <td>claude -p "query"</td> <td>Ask once and exit</td> <td>claude -p "explain the map function in JavaScript"</td> <td>Explanations, technical questions, quick command help</td> </tr> <tr> <td>claude -c</td> <td>Continue the latest conversation</td> <td>claude -c</td> <td>Picking up where you left off after a break</td> </tr> <tr> <td>claude -r</td> <td>Restore a previous conversation</td> <td>claude -r</td> <td>Returning to older work or revisiting a past task</td> </tr> <tr> <td>claude commit</td> <td>Create a Git commit quickly</td> <td>claude commit</td> <td>Generating a clean commit message and committing code changes</td> </tr> <tr> <td>/clear</td> <td>Clear current conversation history</td> <td>> /clear</td> <td>Resetting context when history becomes noisy or irrelevant</td> </tr> <tr> <td>/help</td> <td>Show available commands</td> <td>> /help</td> <td>Looking up syntax or built-in functionality</td> </tr> <tr> <td>exit / Ctrl+C</td> <td>Exit Claude Code</td> <td>> exit / shortcut Ctrl+C</td> <td>Ending the current session</td> </tr> </tbody> </table>

CLAUDE.md: the rulebook for your project

CLAUDE.md is the central configuration file for Claude Code. Think of it as a project handbook for the AI: coding conventions, environment assumptions, scripts, repository rules, and workflow expectations all belong here. It is especially useful for teams that want consistent output across multiple developers.

A typical CLAUDE.md might look like this:

# Bash 命令
- `npm run build`: 项目构建命令
- `npm run typecheck`: 类型检查命令
- `npm run lint`: 代码格式化命令

# 代码风格
- 前端使用ES模块语法(`import/export`),禁用CommonJS(`require`)
- 优先使用解构导入/导出,如`import { foo, bar } from 'baz'`
- JavaScript/TypeScript代码遵循Prettier规范,缩进为2个空格
- 注释使用JSDoc规范,为所有函数、类添加说明

# 工作流程
- 代码修改后必须先执行类型检查,再运行单元测试
- 重大功能修改后,需执行全量测试套件,避免回归问题
- 提交代码前,必须通过lint检查,禁止有格式错误的代码提交

Claude Code supports layered configuration, so you can define rules at different scopes:

<table> <thead> <tr> <th>Path</th> <th>Level</th> <th>Purpose</th> <th>Suggested use</th> </tr> </thead> <tbody> <tr> <td>~/.claude/CLAUDE.md</td> <td>Global</td> <td>Baseline config for all sessions</td> <td>Personal defaults such as general style rules and common commands</td> </tr> <tr> <td>/CLAUDE.md in project root</td> <td>Project</td> <td>Shared project-wide rules</td> <td>Commit it to Git so the whole team follows the same standards</td> </tr> <tr> <td>/CLAUDE.local.md in project root</td> <td>Personal override</td> <td>Personal rules that override project defaults</td> <td>Add it to .gitignore so it does not affect others</td> </tr> <tr> <td>CLAUDE.md in a subdirectory</td> <td>Module</td> <td>Rules for a specific submodule</td> <td>Useful for monorepos, micro-frontends, or isolated feature areas</td> </tr> </tbody> </table>

Loading priority follows the most specific scope first: submodule > project > personal > global.

There is also a convenient way to add rules dynamically. In an interactive session, typing # triggers configuration entry, and Claude Code will ask where to save the rule, such as the project or user level, without requiring manual file edits.

A few useful built-in capabilities

Two features are particularly practical in real work:

  • Image handling: you can paste images directly into the terminal. Claude Code recognizes them as placeholders like [Image #id], which makes it possible to generate code from a design mockup, diagnose an error from a screenshot, or turn a flowchart into implementation logic.
  • Safe YOLO mode: by default, Claude Code asks for permission before running system commands or modifying code. For repetitive automation tasks, you can start it with claude --dangerously-skip-permissions to skip all confirmations. This can speed up batch workflows, but it should be used carefully and preferably only in safe local environments with no important data at risk.

Managing interaction and sessions well

Interactive sessions are the heart of Claude Code, but as a conversation grows, context can become bloated. That raises token usage, dilutes focus, and makes outputs less reliable. Good session management is essential if you want consistent results.

Keep context under control: clear or compact it

Claude Code gives you two main ways to reduce context overload:

  • Clear everything with /clear. This resets the current session and is useful when you are switching tasks or changing requirements significantly.
  • Compact history with /compact [custom summary instruction]. This compresses prior conversation into a smaller summary while preserving the essential context. For example:

/compact 仅保留项目结构和核心开发需求,删除所有调试对话

This approach is especially effective for long-running tasks. You keep the important background while shedding the noise that wastes tokens.

Resume and switch conversations without losing momentum

Interrupted terminals, reboots, and task switching are normal parts of development. Claude Code supports several ways to return to prior work:

  • claude -c restores your most recent interactive session.
  • claude -r shows past conversations with timestamps, message counts, and summaries so you can choose the one you want.
  • /resume lets you switch to another historical session from inside an existing session, which is useful when juggling multiple threads of work.

Shortcuts and interruption controls

A few interaction habits can save time and prevent waste:

  • Type / to see available commands quickly.
  • Use arrow keys to browse previous inputs.
  • Press Tab for command or path autocompletion.
  • Use Option+Enter to insert line breaks for longer prompts.
  • Use Ctrl+C to exit.
  • If Claude Code is already processing and you realize the request is wrong or unclear, press ESC to stop the current task immediately.

That last one matters more than it sounds: interrupting a bad prompt early avoids burning tokens on work you will throw away.

Turn repeatable workflows into custom commands

Many engineering tasks repeat constantly: review a GitHub issue, generate tests, format code according to team conventions, and so on. Claude Code supports custom commands so these workflows can be packaged and reused.

There are two scopes:

  • User-level commands in ~/.claude/commands/
  • Project-level commands in .claude/commands/ under the project root

Each command is a .md file containing the workflow steps. Dynamic inputs can be inserted with $ARGUMENTS. For example:

请按照以下步骤分析并修复指定的GitHub Issue:$ARGUMENTS
1. 使用`gh issue view $ARGUMENTS`命令查看Issue的详细描述、报错信息、复现步骤
2. 基于Issue信息,在代码库中搜索相关的文件和代码片段,定位问题根源
3. 实施必要的代码修改,修复问题,确保修改符合项目的代码风格和开发规范
4. 编写并运行对应的单元测试,验证修复效果,避免回归问题
5. 执行类型检查和lint检查,确保代码无格式错误和类型问题
6. 生成规范的Git提交信息,提交代码
7. 使用`gh pr create`命令创建Pull Request,关联对应的GitHub Issue

You then run these commands with prefixes:

  • User-level: /user:write-tests src/utils/format.js
  • Project-level: /project:fix-github-issue 1234

This is one of the most practical ways to turn Claude Code from a chat assistant into a repeatable engineering tool.

Better prompts, better code

Claude Code’s quality depends not only on the model, but on how clearly you direct it. Strong prompting reduces rework, narrows ambiguity, and helps the model stay aligned with your actual codebase.

Structure prompts with XML tags

Claude responds well to structured prompts. Using XML-style sections clearly separates what the task is, what the relevant context is, and what examples should guide the output.

A useful template is:

<instruction>
  核心任务:明确你希望AI执行的具体操作、达成的目标,使用简洁、准确的语言描述,避免模糊表述。
</instruction>

<context>
  背景信息:提供任务的相关背景,如项目使用的技术栈、框架版本、业务逻辑、团队开发规范、数据库结构、核心文件路径等,帮助AI理解项目上下文。
</context>

<code_example>
  参考示例:提供相关的代码片段、接口规范、实现案例等,帮助AI对齐代码风格、技术选型,生成符合预期的代码。
</code_example>

For example, a Vue 3 component request can be expressed this way:

<instruction>
  使用Vue3 <script setup>语法编写一个用户列表组件,组件名称为UserList,实现用户信息展示、分页功能,支持根据用户名模糊搜索。
</instruction>

<context>
  项目技术栈:Vue3 + Vite + Element Plus,使用ES模块语法,组件样式使用scoped。
  用户数据接口:/api/users,请求方式GET,参数为page(页码)、size(每页条数)、keyword(搜索关键词),返回数据包含list(用户列表)、total(总条数)。
  用户信息字段:id、username、avatar、email、phone、createTime。
</context>

<code_example>
  分页组件使用Element Plus的ElPagination,示例代码:
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="page"
    :page-sizes="[10, 20, 50]"
    :page-size="size"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  />
</code_example>

This format reduces the chance that background information gets mistaken for an instruction.

Pre-activation: make it learn the project before asking it to code

For unfamiliar or complex repositories, jumping straight to implementation is often a mistake. Claude Code can generate plausible code quickly, but if it has not absorbed your project structure, conventions, and business logic, that code may not fit.

A better pattern is a two-step approach:

  1. Have it study and summarize relevant directories, schemas, API docs, or service layers.
  2. Confirm the summary is accurate, then assign the implementation work.

For instance, you might first ask it to inspect /src/services/, summarize the purpose and key functions of each file, and then, only after that, request a migration of user services into /src/modules/user/.

This costs a little more upfront, but usually saves much more time in corrections and debugging.

Trigger deeper reasoning for harder tasks

Claude Code’s default mode is fine for routine work, but architecture decisions, security analysis, performance tuning, and complicated business logic often benefit from stronger reasoning cues.

You can explicitly ask for deeper analysis with phrases such as:

  • think harder
  • ultrathink
  • step-by-step reasoning
  • “perform a comprehensive analysis and reasoning”
  • “consider all possible edge cases”
  • “analyze potential security vulnerabilities and performance issues”
  • “explain the implementation approach step by step”

A request like this is far better than a generic implementation ask:

我需要为我们的API系统实现一个基于OAuth2的认证功能,要求支持密码模式、授权码模式,兼顾安全性和易用性。Think harder about the best approach for implementing this in our codebase,step-by-step reasoning the implementation process,and analyze potential security vulnerabilities in this approach,consider all edge cases we should handle。

Responses take longer, but they are usually more deliberate and complete.

Write real requirements, not vague wishes

One of the main reasons AI output misses the mark is under-specified requests. A prompt like “build a user management page” leaves too much to guess.

The more effective alternative is to provide a lightweight requirements document that includes:

  • The full feature set
  • Technical constraints and versions
  • Interaction and data flow logic
  • Edge cases and error handling expectations
  • Required output format, such as files, tests, or documentation

When possible, diagrams, mockups, or flowcharts help even more.

Development practice: making Claude Code useful in real projects

Knowing commands is not enough. The real payoff comes when Claude Code is embedded into actual software workflows.

Break large jobs into smaller tasks

Context windows and token budgets are finite. If you ask for an entire admin dashboard or a full e-commerce backend in one prompt, you are inviting confusion and inflated token use.

A better approach is to decompose complex work into smaller steps, such as:

  1. Project scaffolding and directory structure
  2. Database schema and model creation
  3. Core APIs such as users, products, and orders
  4. Frontend screens such as login, dashboard, and user management
  5. Testing and bug fixing
  6. Performance tuning and documentation

Let Claude Code finish one chunk before moving to the next. Small tasks like rewriting comments, formatting a file, or fixing a simple syntax error are fine as one-shot requests.

Pass in project context before asking for changes

If you only give Claude Code an instruction and no background, it may produce code that clashes with your stack, style, or architecture.

Useful ways to provide context include:

  1. Via CLAUDE.md: encode stack, commands, and conventions directly.
  2. Via file reading: ask it to inspect package.json, key entry files, core directories, or schema definitions.
  3. Via the prompt itself: explicitly state framework versions, API contracts, auth flow, and error-handling rules.

The more clearly it understands your codebase, the closer the first output will be to something you can actually use.

Use it to generate Linux commands

Claude Code is also helpful when terminal work gets tedious. You can describe a shell task in plain language and ask it to generate the corresponding Linux or Bash command, along with an explanation.

Typical examples include:

  • Listing the top five Python files by line count in a directory tree
  • Finding Markdown files modified in the last 10 days
  • Batch-renaming files with a shared prefix
  • Counting lines of code while excluding blank lines and comments

This is not just a convenience feature. It also helps people learn the command line by seeing both the command and the reasoning behind it.

Cost and model management

Claude Code uses Anthropic models, so token costs matter—especially for teams or frequent users. Managing model choice and monitoring usage helps keep spending under control without sacrificing too much capability.

Choose the right model for the job

The default model is Claude Sonnet 4, which offers a strong balance between performance and cost. It is suitable for most normal development tasks: implementation, debugging, command generation, and moderate design work.

For tougher work such as large-scale architecture, algorithmic implementation, security review, or deep optimization, Claude Opus is available to Anthropic Max users and offers stronger reasoning ability.

You can switch models inside an interactive session with /model, then choose from the available options without restarting.

Monitor token usage in real time

Claude Code provides two layers of cost visibility.

/cost for the current session

Running /cost in a session shows details such as:

  • Total spend in USD
  • API duration and overall terminal session duration
  • Code modification stats, including added and deleted lines
  • Input and output token counts by model, along with cache reads and writes

This is useful when you want to see whether a particular task or prompt style is becoming expensive.

ccusage for broader reporting

For cross-session or cross-project tracking, the recommended tool is ccusage, designed specifically for Claude Code usage analysis.

Install it globally with:

sudo npm install -g ccusage

Useful commands include:

# 基础用法:显示每日token消耗及成本报告(默认)
ccusage
# 按日统计:详细的每日用量、费用、模型使用情况
ccusage daily
# 按月统计:月度汇总报告,适合月度成本核算
ccusage monthly
# 按会话统计:每个历史会话的消耗详情,定位高成本任务
ccusage session
# 实时监控:5小时计费窗口的实时用量仪表盘,动态查看消耗
ccusage blocks --live
# 日期筛选:统计指定时间段的消耗,如2025-07-01至2025-07-10
ccusage daily --since 20250701 --until 20250710
# 格式输出:以JSON格式输出,便于集成到自动化报表
ccusage daily --json
# 模型细分:按不同模型统计费用,分析模型使用效率
ccusage daily --breakdown

With reports like these, it becomes easier to spot expensive patterns and adjust prompts or model selection accordingly.

Advanced capabilities: beyond basic coding assistance

Once the fundamentals are in place, Claude Code becomes much more powerful when combined with Git workflows, external systems, and automation tooling.

Git worktrees: parallel branches without context collisions

Handling bug fixes, new features, and refactors at the same time in one repository can create confusion, especially if multiple branches are involved. Git worktrees solve this by checking out different branches into separate directories while sharing repository history.

Paired with Claude Code, this means one independent session per branch, with clean isolation between tasks.

Typical commands look like this:

   # 创建新分支并生成worktree
   git worktree add ../project-feature-a -b feature-a
   # 使用已有分支生成worktree
   git worktree add ../project-bugfix bugfix-123

Then you can launch separate sessions in each worktree:

   # 处理新功能开发
   cd ../project-feature-a
   claude
   # 处理bug修复(新终端窗口)
   cd ../project-bugfix
   claude

And manage worktrees with:

   # 列出当前所有worktree的目录、分支、状态
   git worktree list
   # 删除指定的worktree(仅清理目录,不删除Git分支)
   git worktree remove ../project-feature-a

A few practical notes:

  • Each worktree is its own environment, so you may need to run setup steps like npm install again.
  • Use meaningful names such as project-auth or project-api-v2.
  • Worktrees share Git history and remotes, so pushing changes remains straightforward.

MCP: connect Claude Code to external systems

MCP, or Model Control Plane, extends Claude Code beyond the repository by letting it connect to tools and services such as Postgres, MySQL, web tools, image tools, or custom local services.

Adding a service looks like this:

# 接入Postgres数据库
claude mcp add pg-server /path/to/postgres-mcp --connection-string "postgresql://user:password@localhost:5432/mydb"
# 接入自定义本地服务
claude mcp add my-service /path/to/my-service-mcp --host 127.0.0.1 --port 3000

You can manage configured services with:

# 列出所有已配置的MCP服务
claude mcp list
# 查看指定MCP服务的详细配置信息
claude mcp get pg-server
# 删除无用的MCP服务
claude mcp remove my-service

Once connected, Claude Code can operate them through natural-language requests, for example querying recent user registrations from a database or calling a local service endpoint and analyzing the returned data structure.

This turns it from a code generator into a cross-platform operator.

GitHub Action integration: bring AI into team collaboration

Claude Code also integrates into GitHub workflows through its GitHub Action tooling. After setup, it can participate in issue handling, PR generation, code review, and follow-up changes.

Installation is initiated from an interactive session with:

/install-github-app

After authorization, team members can call it in GitHub comments with @claude. Typical examples include:

  • @claude implement this feature based on the issue description
  • @claude fix the TypeError in src/components/UserDashboard.vue
  • @claude review this PR and provide optimization suggestions
  • @claude address this feedback in the PR

This kind of automation is especially useful for repetitive collaboration tasks that otherwise eat into engineering time.

Treat it like a Unix tool

Claude Code is not limited to interactive chat. It can also behave like a standard Unix program: accept piped input, emit structured output, and be embedded in scripts or build systems.

Pipe content into it

You can feed logs, source files, or command output straight into Claude Code:

# 分析构建错误日志,定位问题根源
cat build-error.log | claude -p 'concisely explain the root cause of this build error and provide solution'
# 分析Python代码中的bug,生成修复建议
cat src/utils/format.py | claude -p 'analyze this code for bugs and security vulnerabilities, provide detailed fix suggestions'
# 将命令输出作为输入,生成统计报告
ls -l | claude -p 'count the number of files and directories in the current path, generate a detailed statistical report'

Choose output formats for automation

Claude Code supports text, JSON, and streaming JSON output:

# 文本格式:默认格式,适合人工阅读
cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt
# JSON格式:适合集成到自动化脚本、前端展示,包含元数据
cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json
# 流式JSON格式:实时逐条输出,适合处理大文件、长输出
cat app.log | claude -p 'parse this log file for error information' --output-format stream-json

Add it to scripts and pre-commit checks

It can also be embedded into package scripts as an automated reviewer. For example:

{
  "scripts": {
    "lint:claude": "claude -p 'you are a professional code linter, please review the current code changes vs. main branch, report any issues related to code style, typos and logic errors, and provide specific fix suggestions. Report the filename and line number for each issue.'",
    "precommit": "npm run lint:claude"
  }
}

Running npm run lint:claude gives you AI-assisted review, and using it as a precommit hook adds a guardrail before code lands in the repository.

What Claude Code changes in practice

The most important shift Claude Code introduces is not that it writes code for you. It is that it changes how coding work is coordinated between developer and machine.

Instead of living as an isolated assistant that answers questions or drafts snippets, it can sit inside the actual development loop: terminal operations, editor workflows, project rules, version control, GitHub collaboration, external service access, and automation pipelines.

To get the most from it, a developer needs more than command familiarity. Clear prompts, good session hygiene, thoughtful task decomposition, and sensible cost control make the difference between a flashy demo and a dependable workflow.

As AI tools continue to improve, the most effective development model is increasingly not “human or AI,” but “human with AI embedded into the process.” Claude Code is at its best when it helps remove repetitive work, keeps context organized, and frees developers to spend more time on architecture, product logic, and technical judgment.