logo
36

Claude Code Complete Guide

⏱️ 25 min

Claude Code Complete Usage Guide

Claude Code isn't another AI IDE. It's a CLI-native intelligent coding assistant. This guide is compiled from official docs and covers installation, configuration, MCP integration, security management, and everything in between.


Claude Code vs AI IDE Comparison

Pain PointCursor & AI IDEsClaude Code (CLI)
AI capabilityDumbed down for cost reasonsNative Claude 4 Sonnet/Opus, completely uncut
Tool callsOnly 25, complex tasks get interruptedUnlimited tool calls, runs to completion
ContextSmall window, can't grok large projects200K+ context, sees the entire project
Agent abilityLong tasks get interruptedFully autonomous agent, start to finish
DebuggingCan only see codeReads system logs directly, real-time debug

Installation

macOS:

curl -fsSL https://aicodewith.com/claudecode/resources/install-script-macos | bash

Linux:

curl -fsSL https://aicodewith.com/claudecode/resources/install-script-linux | bash

Windows (WSL):

# Install WSL2
wsl --install

# Install Ubuntu from Microsoft Store, then run
curl -fsSL https://aicodewith.com/claudecode/resources/install-script-wsl | bash

Option 2: NPM Official Install

# Global install
npm install -g @anthropic-ai/claude-code

# Verify version
claude --version

First-Time Setup

API Configuration (Mirror site users can skip)

# Get API key from the official site
export ANTHROPIC_API_KEY="sk-your-key-here"

# Pick your shell
# Bash
echo 'export ANTHROPIC_API_KEY="sk-your-key-here"' >> ~/.bashrc
source ~/.bashrc

# Zsh
echo 'export ANTHROPIC_API_KEY="sk-your-key-here"' >> ~/.zshrc
source ~/.zshrc

Basic Config

# Change default settings
claude config set -g model claude-sonnet-4
claude config set -g verbose true
claude config set -g outputFormat text

# Test installation
claude "Hello, Claude!"
claude /doctor

Security Settings (Optional)

export DISABLE_TELEMETRY=1                 # Don't send usage stats
export DISABLE_ERROR_REPORTING=1           # Don't send error logs
export DISABLE_NON_ESSENTIAL_MODEL_CALLS=1 # Save tokens

# Restrict tool permissions
claude config set allowedTools "Edit,View"

Basic Commands

Core Interaction

claude                           # Launch
claude "fix this bug"            # One-shot command
claude -p "<prompt>"             # Single print mode
cat file | claude -p "<prompt>"  # Large file reading
claude update                    # Update client
claude mcp                       # MCP wizard

Conversation Commands

claude -c              # Continue last conversation
claude -r <id>         # Resume by session ID
claude --resume <id>   # Resume long conversation
claude --resume <name> # Resume by name

Slash Commands

CommandFunction
/helpList all slash commands
/add-dirAdd working directories
/clearClear chat history
/compactCompress context
/configConfig menu
/costToken cost stats
/doctorClient integrity check
/exitExit Claude Code
/initInit project, generate CLAUDE.md
/mcpView MCP list and status
/memoryEdit memory
/modelSwitch model
/permissionsModify tool permissions
/reviewRequest code review
/sessionsList sessions
/statusSystem/account status
/vimToggle vim mode

MCP Integration

MCP extends Claude's capabilities by connecting to external services, databases, and APIs.

Basic MCP Commands

claude mcp list              # List existing MCP services
claude mcp add <name> <cmd>  # Add new MCP
claude mcp remove <name>     # Remove MCP

Config file location: ~/.claude.json

Common MCP Services

Git MCP:

npm install -g git-mcp-server
claude mcp add git "git-mcp-server"
claude mcp add github "github-mcp-server --token $GITHUB_TOKEN"

Database MCP:

npm install -g postgres-mcp-server
export POSTGRES_URL="postgresql://user:password@localhost:5432/mydb"
claude mcp add postgres "postgres-mcp-server --url $POSTGRES_URL"

MCP Tool Permissions

# Grant specific MCP permissions
claude --allowedTools "mcp__git__commit,mcp__git__push"

# Wildcard permissions
claude --allowedTools "mcp__postgres__*"

# Combine MCP with built-in tools
claude --allowedTools "Edit,View,mcp__git__*"

Configuration System

Global Config

Location: ~/.claude.json

{
	"model": "claude-sonnet-4",
	"verbose": true,
	"outputFormat": "text",
	"allowedTools": ["Edit", "View"],
	"disallowedTools": []
}

Project Config

Location: .claude/settings.json

{
	"model": "claude-sonnet-4",
	"systemPrompt": "You are a senior developer working on this project",
	"allowedTools": ["Edit", "View", "Bash(git:*)", "Bash(npm:*)"]
}

Environment Variables

VariableDefaultEffect
DISABLE_NON_ESSENTIAL_MODEL_CALLS0Skip auto-summaries, save tokens
MAX_THINKING_TOKENS~30-40kSet max thinking tokens
DISABLE_TELEMETRY0Don't send usage stats
CLAUDE_CODE_USE_BEDROCK0Auth via AWS Bedrock
CLAUDE_CODE_USE_VERTEX0Auth via Google Vertex AI
HTTP_PROXYunsetHTTP proxy
HTTPS_PROXYunsetHTTPS proxy

Security & Permission Management

Permission Levels

LevelDescriptionRisk
InteractivePrompts for each actionLow
AllowlistPre-approved tools onlyMedium
DangerousSkip all permissionsHigh

Tool Permission Management

# Grant specific tool permissions
claude --allowedTools "Edit,View"

# Scoped permissions (git only)
claude --allowedTools "Bash(git:*)"

# Multiple scopes
claude --allowedTools "Bash(git:*),Bash(npm:*)"

# Full permission mode (dangerous!)
claude --dangerously-skip-permissions

1. Restrict to specific permissions

# Good: specific permissions
claude --allowedTools "Edit,View,Bash(git:status)"

# Bad: too broad
claude --allowedTools "Bash"

2. Protect sensitive data

# Good: use environment variables
export DATABASE_URL="postgresql://user:pass@host/db"

# Bad: hardcoded credentials
claude "connect to postgresql://user:password123@host/db"

3. Audit permissions regularly

claude config get allowedTools
claude config get disallowedTools
claude config list

Thinking Mode

Trigger deeper thinking with prompt keywords:

Thinking DepthPrompt Keywords
1think
2think about it, think a lot, think deeply, think hard
3think harder, think intensely, ultrathink

Example:

claude -p "We have a tricky concurrency bug. ultrathink and propose a fix."
  • Keywords can appear anywhere in the prompt
  • If multiple keywords exist, highest level wins

Config Command Reference

claude config list              # Show all current settings
claude config get <key>         # Show specific setting
claude config set -g <key> <value>  # Set global value
claude config add -g <key> <value>  # Append to array setting
claude config remove -g <key> <value>  # Remove from array

Note: -g flag means global setting. Without it, settings apply to current project only.

Common Config Keys

KeyCommon ValuesFunction
themedark, lightCLI theme
verbosetrue/falseShow full output
autoUpdatestrue/falseAuto-update
autoCompactEnabledtrue/falseAuto-compress chat
diffToolmeld, diffDiff tool
parallelTasksCount1-8Concurrent task count
autoConnectIdetrue/falseAuto-connect IDE

Team Collaboration & CI/CD

GitHub Actions Integration

name: Claude Code Review
on:
    pull_request:
        branches: [main, develop]

jobs:
    claude-review:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v4

            - name: Setup Node.js 18
              uses: actions/setup-node@v4
              with:
                  node-version: '18'

            - name: Install Claude Code
              run: npm install -g @anthropic-ai/claude-code

            - name: Review PR
              env:
                  ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
              run: |
                  claude -p "Review changes for security issues and bugs" \
                    --allowedTools "View" \
                    --output-format json > review-results.json

            - name: Upload results
              uses: actions/upload-artifact@v4
              with:
                  name: claude-review
                  path: review-results.json

Local Git Pre-commit Hook

#!/usr/bin/env bash
# .git/hooks/pre-commit (chmod +x)

staged=$(git diff --cached --name-only --diff-filter=ACM)
[ -z "$staged" ] && exit 0

payload=$(echo "$staged" | xargs cat)

analysis=$(echo "$payload" | \
  claude -p "Review these changes for issues before commit" \
    --allowedTools "View" \
    --output-format json)

if echo "$analysis" | jq -e '.critical_issues[]' >/dev/null 2>&1; then
  echo "❌ Critical issues found – commit blocked"
  exit 1
fi

echo "✅ Claude analysis passed"

Advanced Features

Persistent Memory (CLAUDE.md)

Generated by /init, lives at the project root:

# Project: My Application

## Overview

This is a React/Node.js application with PostgreSQL database.

## Architecture

-   Frontend: React 18 with TypeScript
-   Backend: Node.js with Express
-   Database: PostgreSQL 14

## Development Guidelines

-   Use TypeScript for all new code
-   Follow ESLint configuration
-   Write tests for new features

Memory Command

claude /memory           # Edit project memory
claude /memory view      # View current memory

Multi-Directory Workspace

# Add multiple directories
claude --add-dir ../frontend ../backend ../shared

# Project-level analysis
claude "analyze the entire application architecture"

Summary

Claude Code is a powerful CLI coding assistant. Core strengths:

  • Native Claude 4 - completely uncut
  • Unlimited tool calls - complex tasks run to completion
  • 200K+ context - sees the entire project at once
  • Fully autonomous agent - start-to-finish execution
  • MCP extensions - connect external services and databases
  • CI/CD integration - automated code review

Use this guide as a reference -- look up the relevant section when you need it.


Original source: Zhihu @Cluade2Claude | Compiled 2025-10-18

📚 相关资源