Skip to content

Claude How ToClaude How To

Tham Chiếu CLI / CLI Reference

Tổng Quan / Overview

CLI Claude Code (Command Line Interface) là cách chính để tương tác với Claude Code. Nó cung cấp các tùy chọn mạnh mẽ để chạy các truy vấn, quản lý sessions, cấu hình mô hình, và tích hợp Claude vào workflows phát triển của bạn.

Kiến Trúc / Architecture

Các Lệnh CLI / CLI Commands

LệnhMô TảVí Dụ
claudeBắt đầu REPL tương tácclaude
claude "query"Bắt đầu REPL với prompt ban đầuclaude "explain this project"
claude -p "query"Chế độ in - query sau đó thoátclaude -p "explain this function"
cat file | claude -p "query"Xử lý nội dung được pipecat logs.txt | claude -p "explain"
claude -cTiếp tục hội thoại gần đây nhấtclaude -c
claude -c -p "query"Tiếp tục trong chế độ inclaude -c -p "check for type errors"
claude -r "<session>" "query"Resume session theo ID hoặc tênclaude -r "auth-refactor" "finish this PR"
claude updateCập nhật đến phiên bản mới nhấtclaude update
claude mcpCấu hình MCP serversXem Tài liệu MCP
claude mcp serveChạy Claude Code như một MCP serverclaude mcp serve
claude agentsLiệt kê tất cả các subagents được cấu hìnhclaude agents
claude auto-mode defaultsIn các quy tắc mặc định chế độ tự động như JSONclaude auto-mode defaults
claude remote-controlBắt đầu server Remote Controlclaude remote-control
claude pluginQuản lý plugins (cài đặt, kích hoạt, vô hiệu hóa)claude plugin install my-plugin
claude auth loginĐăng nhập (hỗ trợ --email, --sso)claude auth login --email user@example.com
claude auth logoutĐăng xuất khỏi tài khoản hiện tạiclaude auth logout
claude auth statusKiểm tra trạng thái auth (exit 0 nếu đã đăng nhập, 1 nếu chưa)claude auth status

Các Cờ Chính / Core Flags

CờMô TảVí Dụ
-p, --printIn phản hồi mà không có chế độ tương tácclaude -p "query"
-c, --continueTải hội thoại gần đây nhấtclaude --continue
-r, --resumeResume session cụ thể theo ID hoặc tênclaude --resume auth-refactor
-v, --versionIn số phiên bảnclaude -v
-w, --worktreeBắt đầu trong git worktree cô lậpclaude -w
-n, --nameTên hiển thị sessionclaude -n "auth-refactor"
--from-pr <number>Resume sessions được liên kết đến GitHub PRclaude --from-pr 42
--remote "task"Tạo session web trên claude.aiclaude --remote "implement API"
--remote-control, --rcSession tương tác với Remote Controlclaude --rc
--teleportResume session web cục bộclaude --teleport
--teammate-modeChế độ hiển thị agent teamclaude --teammate-mode tmux
--bareChế độ tối thiểu (bỏ qua hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--enable-auto-modeMở khóa chế độ quyền tự độngclaude --enable-auto-mode
--channelsĐăng ký các plugin kênh MCPclaude --channels discord,telegram
--chrome / --no-chromeBật/tắt tích hợp trình duyệt Chromeclaude --chrome
--effortĐặt mức độ suy nghĩclaude --effort high
--init / --init-onlyChạy các hooks khởi tạoclaude --init
--maintenanceChạy các hooks bảo trì và thoátclaude --maintenance
--disable-slash-commandsVô hiệu hóa tất cả skills và lệnh slashclaude --disable-slash-commands
--no-session-persistenceVô hiệu hóa lưu session (chế độ in)claude -p --no-session-persistence "query"

Tương Tác vs Chế Độ In / Interactive vs Print Mode

Chế Độ Tương Tác (mặc định):

bash
# Bắt đầu session tương tác
claude

# Bắt đầu với prompt ban đầu
claude "explain the authentication flow"

Chế Độ In (không tương tác):

bash
# Query đơn, sau đó thoát
claude -p "what does this function do?"

# Xử lý nội dung file
cat error.log | claude -p "explain this error"

# Chuỗi với các công cụ khác
claude -p "list todos" | grep "URGENT"

Mô Hình & Cấu Hình / Model & Configuration

CờMô TảVí Dụ
--modelĐặt mô hình (sonnet, opus, haiku, hoặc tên đầy đủ)claude --model opus
--fallback-modelFallback mô hình tự động khi quá tảiclaude -p --fallback-model sonnet "query"
--agentChỉ định agent cho sessionclaude --agent my-custom-agent
--agentsĐịnh nghĩa subagents tùy chỉnh qua JSONXem Tác Nhân Con
--effortĐặt mức độ effort (low, medium, high, max)claude --effort high

Ví Dụ Chọn Mô Hình / Model Selection Examples

bash
# Sử dụng Opus 4.6 cho các tác vụ phức tạp
claude --model opus "design a caching strategy"

# Sử dụng Haiku 4.5 cho các tác vụ nhanh
claude --model haiku -p "format this JSON"

# Tên mô hình đầy đủ
claude --model claude-sonnet-4-6-20250929 "review this code"

# Với fallback để đảm bảo độ tin cậy
claude -p --model opus --fallback-model sonnet "analyze architecture"

# Sử dụng opusplan (Opus plans, Sonnet executes)
claude --model opusplan "design and implement the caching layer"

Tùy Chỉnh System Prompt / System Prompt Customization

CờMô TảVí Dụ
--system-promptThay thế toàn bộ prompt mặc địnhclaude --system-prompt "You are a Python expert"
--system-prompt-fileTải prompt từ file (chế độ in)claude -p --system-prompt-file ./prompt.txt "query"
--append-system-promptAppend vào prompt mặc địnhclaude --append-system-prompt "Always use TypeScript"

Ví Dụ System Prompt / System Prompt Examples

bash
# Complete custom persona
claude --system-prompt "You are a senior security engineer. Focus on vulnerabilities."

# Append specific instructions
claude --append-system-prompt "Always include unit tests with code examples"

# Load complex prompt from file
claude -p --system-prompt-file ./prompts/code-reviewer.txt "review main.py"

So Sánh Các Cờ System Prompt / System Prompt Flags Comparison

CờHành ViInteractivePrint
--system-promptThay thế toàn bộ system prompt
--system-prompt-fileThay thế bằng prompt từ file
--append-system-promptThêm vào system prompt mặc định

Chỉ sử dụng --system-prompt-file trong chế độ in. Trong chế độ tương tác, sử dụng --system-prompt hoặc --append-system-prompt.

Công Cụ & Quản Lý Quyền / Tool & Permission Management

CờMô TảVí Dụ
--toolsHạn chế các công cụ có sẵnclaude -p --tools "Bash,Edit,Read" "query"
--allowedToolsCác công cụ thực thi mà không cần prompt"Bash(git log:*)" "Read"
--disallowedToolsCác công cụ bị xóa khỏi ngữ cảnh"Bash(rm:*)" "Edit"
--dangerously-skip-permissionsBỏ qua tất cả các prompt quyềnclaude --dangerously-skip-permissions
--permission-modeBắt đầu trong chế độ quyền được chỉ địnhclaude --permission-mode auto
--permission-prompt-toolCông cụ MCP để xử lý quyềnclaude -p --permission-prompt-tool mcp_auth "query"
--enable-auto-modeMở khóa chế độ quyền tự độngclaude --enable-auto-mode

Ví Dụ Quyền / Permission Examples

bash
# Chế độ read-only để review code
claude --permission-mode plan "review this codebase"

# Hạn chế đến các công cụ an toàn chỉ
claude --tools "Read,Grep,Glob" -p "find all TODO comments"

# Cho phép các lệnh git cụ thể mà không cần prompts
claude --allowedTools "Bash(git status:*)" "Bash(git log:*)"

# Chặn các thao tác nguy hiểm
claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"

Đầu Ra & Định Dạng / Output & Format

CờMô TảTùy ChọnVí Dụ
--output-formatChỉ định định dạng đầu ra (chế độ in)text, json, stream-jsonclaude -p --output-format json "query"
--input-formatChỉ định định dạng đầu vào (chế độ in)text, stream-jsonclaude -p --input-format stream-json
--verboseBật ghi nhật chi tiếtclaude --verbose
--include-partial-messagesBao gồm các sự kiện streamingYêu cầu stream-jsonclaude -p --output-format stream-json --include-partial-messages "query"
--json-schemaNhận JSON được validate theo schemaclaude -p --json-schema '{"type":"object"}' "query"
--max-budget-usdGiới hạn chi phí tối đa cho chế độ inclaude -p --max-budget-usd 5.00 "query"

Ví Dụ Định Dạng Đầu Ra / Output Format Examples

bash
# Plain text (mặc định)
claude -p "explain this code"

# JSON cho sử dụng lập trình
claude -p --output-format json "list all functions in main.py"

# Streaming JSON để xử lý real-time
claude -p --output-format stream-json "generate a long report"

# Structured output với schema validation
claude -p --json-schema '{"type":"object","properties":{"bugs":{"type":"array"}}}' \
  "find bugs in this code and return as JSON"

Workspace & Thư Mục / Workspace & Directory

CờMô TảVí Dụ
--add-dirThêm thư mục làm việc bổ sungclaude --add-dir ../apps ../lib
--setting-sourcesNguồn cài đặt phân cách bằng dấu phẩyclaude --setting-sources user,project
--settingsTải cài đặt từ file hoặc JSONclaude --settings ./settings.json
--plugin-dirTải plugins từ thư mục (có thể lặp lại)claude --plugin-dir ./my-plugin

Ví Dụ Đa Thư Mục / Multi-Directory Example

bash
# Làm việc trên nhiều thư mục project
claude --add-dir ../frontend ../backend ../shared "find all API endpoints"

# Tải custom settings
claude --settings '{"model":"opus","verbose":true}' "complex task"

Cấu Hình MCP / MCP Configuration

CờMô TảVí Dụ
--mcp-configTải MCP servers từ JSONclaude --mcp-config ./mcp.json
--strict-mcp-configChỉ sử dụng MCP config được chỉ địnhclaude --strict-mcp-config --mcp-config ./mcp.json
--channelsĐăng ký các plugin kênh MCPclaude --channels discord,telegram

Ví Dụ MCP / MCP Examples

bash
# Tải GitHub MCP server
claude --mcp-config ./github-mcp.json "list open PRs"

# Strict mode - chỉ servers được chỉ định
claude --strict-mcp-config --mcp-config ./production-mcp.json "deploy to staging"

Quản Lý Session / Session Management

CờMô TảVí Dụ
--session-idSử dụng session ID cụ thể (UUID)claude --session-id "550e8400-..."
--fork-sessionTạo session mới khi resumeclaude --resume abc123 --fork-session

Ví Dụ Session / Session Examples

bash
# Tiếp tục hội thoại cuối
claude -c

# Resume named session
claude -r "feature-auth" "continue implementing login"

# Fork session để thử nghiệm
claude --resume feature-auth --fork-session "try alternative approach"

# Sử dụng specific session ID
claude --session-id "550e8400-e29b-41d4-a716-446655440000" "continue"

Session Fork

Tạo một nhánh từ session hiện có để thử nghiệm:

bash
# Fork một session để thử cách tiếp cận khác
claude --resume abc123 --fork-session "try alternative implementation"

# Fork với custom message
claude -r "feature-auth" --fork-session "test with different architecture"

Trường Hợp Sử Dụng:

  • Thử các implementation khác mà không mất session gốc
  • Thử nghiệm với các cách tiếp cận khác nhau song song
  • Tạo các nhánh từ công việc thành công cho các biến thể
  • Test các thay đổi breaking mà không ảnh hưởng đến main session

Session gốc vẫn không thay đổi, và fork trở thành một session độc lập mới.

Tính Năng Nâng Cao / Advanced Features

CờMô TảVí Dụ
--chromeBật tích hợp trình duyệt Chromeclaude --chrome
--no-chromeTắt tích hợp trình duyệt Chromeclaude --no-chrome
--ideTự động kết nối đến IDE nếu cóclaude --ide
--max-turnsGiới hạn agentic turns (non-interactive)claude -p --max-turns 3 "query"
--debugBật debug mode với filteringclaude --debug "api,mcp"
--enable-lsp-loggingBật verbose LSP loggingclaude --enable-lsp-logging
--betasBeta headers cho API requestsclaude --betas interleaved-thinking
--plugin-dirTải plugins từ thư mục (có thể lặp lại)claude --plugin-dir ./my-plugin
--enable-auto-modeMở khóa chế độ quyền tự độngclaude --enable-auto-mode
--effortĐặt mức độ suy nghĩclaude --effort high
--bareChế độ tối thiểu (bỏ qua hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--channelsĐăng ký các plugin kênh MCPclaude --channels discord
--tmuxTạo tmux session cho worktreeclaude --tmux
--fork-sessionTạo session ID mới khi resumeclaude --resume abc --fork-session
--max-budget-usdChi phí tối đa (chế độ in)claude -p --max-budget-usd 5.00 "query"
--json-schemaValidate JSON outputclaude -p --json-schema '{"type":"object"}' "q"

Ví Dụ Nâng Cao / Advanced Examples

bash
# Giới hạn autonomous actions
claude -p --max-turns 5 "refactor this module"

# Debug API calls
claude --debug "api" "test query"

# Bật IDE integration
claude --ide "help me with this file"

Cấu Hình Agents / Agents Configuration

Cờ --agents chấp nhận một JSON object định nghĩa custom subagents cho một session.

Agents JSON Format

json
{
  "agent-name": {
    "description": "Required: when to invoke this agent",
    "prompt": "Required: system prompt for the agent",
    "tools": ["Optional", "array", "of", "tools"],
    "model": "optional: sonnet|opus|haiku"
  }
}

Các Trường Bắt Buộc:

  • description - Mô tả tự nhiên khi nào sử dụng agent này
  • prompt - System prompt định nghĩa role và hành vi của agent

Các Trường Tùy Chọn:

  • tools - Array của available tools (kế thừa tất cả nếu omit)
    • Format: ["Read", "Grep", "Glob", "Bash"]
  • model - Model sử dụng: sonnet, opus, hoặc haiku

Complete Agents Example

json
{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes.",
    "tools": ["Read", "Edit", "Bash", "Grep"],
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist for generating guides.",
    "prompt": "You are a technical writer. Create clear, comprehensive documentation.",
    "tools": ["Read", "Write"],
    "model": "haiku"
  }
}

Ví Dụ Lệnh Agents / Agents Command Examples

bash
# Define custom agents inline
claude --agents '{
  "security-auditor": {
    "description": "Security specialist for vulnerability analysis",
    "prompt": "You are a security expert. Find vulnerabilities and suggest fixes.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "opus"
  }
}' "audit this codebase for security issues"

# Load agents from file
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

# Combine with other flags
claude -p --agents "$(cat agents.json)" --model sonnet "analyze performance"

Agent Priority

Khi nhiều agent definitions tồn tại, chúng được load theo thứ tự ưu tiên này:

  1. CLI-defined (--agents flag) - Session-specific
  2. User-level (~/.claude/agents/) - All projects
  3. Project-level (.claude/agents/) - Current project

CLI-defined agents override cả user và project agents cho session.


Các Trường Hợp Sử Dụng Giá Trị Cao / High-Value Use Cases

1. Tích Hợp CI/CD

Sử dụng Claude Code trong CI/CD pipelines để tự động review code, testing, và documentation.

GitHub Actions Example:

yaml
name: AI Code Review

on: [pull_request]

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

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

      - name: Run Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p --output-format json \
            --max-turns 1 \
            "Review the changes in this PR for:
            - Security vulnerabilities
            - Performance issues
            - Code quality
            Output as JSON with 'issues' array" > review.json

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            // Process and post review comments

Jenkins Pipeline:

groovy
pipeline {
    agent any
    stages {
        stage('AI Review') {
            steps {
                sh '''
                    claude -p --output-format json \
                      --max-turns 3 \
                      "Analyze test coverage and suggest missing tests" \
                      > coverage-analysis.json
                '''
            }
        }
    }
}

2. Script Piping

Xử lý files, logs, và data thông qua Claude để phân tích.

Phân Tích Log:

bash
# Analyze error logs
tail -1000 /var/log/app/error.log | claude -p "summarize these errors and suggest fixes"

# Find patterns in access logs
cat access.log | claude -p "identify suspicious access patterns"

# Analyze git history
git log --oneline -50 | claude -p "summarize recent development activity"

Xử Lý Code:

bash
# Review a specific file
cat src/auth.ts | claude -p "review this authentication code for security issues"

# Generate documentation
cat src/api/*.ts | claude -p "generate API documentation in markdown"

# Find TODOs and prioritize
grep -r "TODO" src/ | claude -p "prioritize these TODOs by importance"

3. Multi-Session Workflows

Quản lý các project phức tạp với nhiều conversation threads.

bash
# Start a feature branch session
claude -r "feature-auth" "let's implement user authentication"

# Later, continue the session
claude -r "feature-auth" "add password reset functionality"

# Fork to try an alternative approach
claude --resume feature-auth --fork-session "try OAuth instead"

# Switch between different feature sessions
claude -r "feature-payments" "continue with Stripe integration"

4. Custom Agent Configuration

Định nghĩa specialized agents cho workflows của team bạn.

bash
# Save agents config to file
cat > ~/.claude/agents.json << 'EOF'
{
  "reviewer": {
    "description": "Code reviewer for PR reviews",
    "prompt": "Review code for quality, security, and maintainability.",
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist",
    "prompt": "Generate clear, comprehensive documentation.",
    "model": "sonnet"
  },
  "refactorer": {
    "description": "Code refactoring expert",
    "prompt": "Suggest and implement clean code refactoring.",
    "tools": ["Read", "Edit", "Glob"]
  }
}
EOF

# Use agents in session
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

5. Batch Processing

Xử lý nhiều queries với settings nhất quán.

bash
# Process multiple files
for file in src/*.ts; do
  echo "Processing $file..."
  claude -p --model haiku "summarize this file: $(cat $file)" >> summaries.md
done

# Batch code review
find src -name "*.py" -exec sh -c '
  echo "## $1" >> review.md
  cat "$1" | claude -p "brief code review" >> review.md
' _ {} \;

# Generate tests for all modules
for module in $(ls src/modules/); do
  claude -p "generate unit tests for src/modules/$module" > "tests/$module.test.ts"
done

6. Phát Triển Có Nhận Thức Bảo Mật

Sử dụng permission controls cho hoạt động an toàn.

bash
# Read-only security audit
claude --permission-mode plan \
  --tools "Read,Grep,Glob" \
  "audit this codebase for security vulnerabilities"

# Block dangerous commands
claude --disallowedTools "Bash(rm:*)" "Bash(curl:*)" "Bash(wget:*)" \
  "help me clean up this project"

# Restricted automation
claude -p --max-turns 2 \
  --allowedTools "Read" "Glob" \
  "find all hardcoded credentials"

7. JSON API Integration

Sử dụng Claude như một programmable API cho các công cụ của bạn với jq parsing.

bash
# Get structured analysis
claude -p --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array"},"complexity":{"type":"string"}}}' \
  "analyze main.py and return function list with complexity rating"

# Integrate with jq for processing
claude -p --output-format json "list all API endpoints" | jq '.endpoints[]'

# Use in scripts
RESULT=$(claude -p --output-format json "is this code secure? answer with {secure: boolean, issues: []}" < code.py)
if echo "$RESULT" | jq -e '.secure == false' > /dev/null; then
  echo "Security issues found!"
  echo "$RESULT" | jq '.issues[]'
fi

Ví Dụ jq Parsing

Parse và xử lý JSON output của Claude bằng jq:

bash
# Extract specific fields
claude -p --output-format json "analyze this code" | jq '.result'

# Filter array elements
claude -p --output-format json "list issues" | jq -r '.issues[] | select(.severity=="high")'

# Extract multiple fields
claude -p --output-format json "describe the project" | jq -r '.{name, version, description}'

# Convert to CSV
claude -p --output-format json "list functions" | jq -r '.functions[] | [.name, .lineCount] | @csv'

# Conditional processing
claude -p --output-format json "check security" | jq 'if .vulnerabilities | length > 0 then "UNSAFE" else "SAFE" end'

# Extract nested values
claude -p --output-format json "analyze performance" | jq '.metrics.cpu.usage'

# Process entire array
claude -p --output-format json "find todos" | jq '.todos | length'

# Transform output
claude -p --output-format json "list improvements" | jq 'map({title: .title, priority: .priority})'

Các Mô Hình / Models

Claude Code hỗ trợ nhiều mô hình với các capabilities khác nhau:

Mô HìnhIDContext WindowGhi Chú
Opus 4.6claude-opus-4-61M tokensMost capable, adaptive effort levels
Sonnet 4.6claude-sonnet-4-61M tokensBalanced speed and capability
Haiku 4.5claude-haiku-4-51M tokensFastest, best for quick tasks

Chọn Mô Hình / Model Selection

bash
# Use short names
claude --model opus "complex architectural review"
claude --model sonnet "implement this feature"
claude --model haiku -p "format this JSON"

# Use opusplan alias (Opus plans, Sonnet executes)
claude --model opusplan "design and implement the API"

# Toggle fast mode during session
/fast

Effort Levels (Opus 4.6)

Opus 4.6 hỗ trợ adaptive reasoning với các effort levels:

bash
# Set effort level via CLI flag
claude --effort high "complex review"

# Set effort level via slash command
/effort high

# Set effort level via environment variable
export CLAUDE_CODE_EFFORT_LEVEL=high   # low, medium, high, or max (Opus 4.6 only)

Từ khóa "ultrathink" trong prompts kích hoạt deep reasoning. Mức max effort chỉ dành cho Opus 4.6.


Các Biến Môi Trường Quan Trọng / Key Environment Variables

BiếnMô Tả
ANTHROPIC_API_KEYAPI key cho authentication
ANTHROPIC_MODELOverride default model
ANTHROPIC_CUSTOM_MODEL_OPTIONCustom model option for API
ANTHROPIC_DEFAULT_OPUS_MODELOverride default Opus model ID
ANTHROPIC_DEFAULT_SONNET_MODELOverride default Sonnet model ID
ANTHROPIC_DEFAULT_HAIKU_MODELOverride default Haiku model ID
MAX_THINKING_TOKENSSet extended thinking token budget
CLAUDE_CODE_EFFORT_LEVELSet effort level (low/medium/high/max)
CLAUDE_CODE_SIMPLEMinimal mode, set by --bare flag
CLAUDE_CODE_DISABLE_AUTO_MEMORYDisable automatic CLAUDE.md updates
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background task execution
CLAUDE_CODE_DISABLE_CRONDisable scheduled/cron tasks
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONSDisable git-related instructions
CLAUDE_CODE_DISABLE_TERMINAL_TITLEDisable terminal title updates
CLAUDE_CODE_DISABLE_1M_CONTEXTDisable 1M token context window
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACKDisable non-streaming fallback
CLAUDE_CODE_ENABLE_TASKSEnable task list feature
CLAUDE_CODE_TASK_LIST_IDNamed task directory shared across sessions
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTIONToggle prompt suggestions (true/false)
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMSEnable experimental agent teams
CLAUDE_CODE_NEW_INITUse new initialization flow
CLAUDE_CODE_SUBAGENT_MODELModel for subagent execution
CLAUDE_CODE_PLUGIN_SEED_DIRDirectory for plugin seed files
CLAUDE_CODE_SUBPROCESS_ENV_SCRUBEnv vars to scrub from subprocesses
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEOverride auto-compaction percentage
CLAUDE_STREAM_IDLE_TIMEOUT_MSStream idle timeout in milliseconds
SLASH_COMMAND_TOOL_CHAR_BUDGETCharacter budget for slash command tools
ENABLE_TOOL_SEARCHEnable tool search capability
MAX_MCP_OUTPUT_TOKENSMaximum tokens for MCP tool output

Tham Chiếu Nhanh / Quick Reference

Các Lệnh Phổ Biến Nhất

bash
# Interactive session
claude

# Quick question
claude -p "how do I..."

# Continue conversation
claude -c

# Process a file
cat file.py | claude -p "review this"

# JSON output for scripts
claude -p --output-format json "query"

Kết Hợp Cờ / Flag Combinations

Trường Hợp Sử DụngLệnh
Quick code review`cat file
Structured outputclaude -p --output-format json "query"
Safe explorationclaude --permission-mode plan
Autonomous with safetyclaude --enable-auto-mode --permission-mode auto
CI/CD integrationclaude -p --max-turns 3 --output-format json
Resume workclaude -r "session-name"
Custom modelclaude --model opus "complex task"
Minimal modeclaude --bare "quick query"
Budget-capped runclaude -p --max-budget-usd 2.00 "analyze code"

Xử Lý Sự Cố / Troubleshooting

Command Not Found

Vấn đề: claude: command not found

Giải pháp:

  • Cài đặt Claude Code: npm install -g @anthropic-ai/claude-code
  • Kiểm tra PATH bao gồm npm global bin directory
  • Thử chạy với full path: npx claude

API Key Issues

Vấn đề: Authentication failed

Giải pháp:

  • Đặt API key: export ANTHROPIC_API_KEY=your-key
  • Kiểm tra key hợp lệ và có đủ credits
  • Xác minh key permissions cho model được yêu cầu

Session Not Found

Vấn đề: Cannot resume session

Giải pháp:

  • Liệt kê các sessions có sẵn để tìm đúng tên/ID
  • Sessions có thể hết hạn sau một thời gian không hoạt động
  • Sử dụng -c để tiếp tục session gần nhất

Output Format Issues

Vấn đề: JSON output is malformed

Giải pháp:

  • Sử dụng --json-schema để enforce structure
  • Thêm instructions JSON rõ ràng trong prompt
  • Sử dụng --output-format json (không chỉ yêu cầu JSON trong prompt)

Permission Denied

Vấn đề: Tool execution blocked

Giải pháp:

  • Kiểm tra --permission-mode setting
  • Xem lại --allowedTools--disallowedTools flags
  • Sử dụng --dangerously-skip-permissions cho automation (cẩn thận)

Tài Nguyên Thêm / Additional Resources


Phần của series hướng dẫn Claude How To


Cập Nhật Lần Cuối: Tháng 4 năm 2026 Phiên Bản Claude Code: 2.1+ Các Mô Hình Tương Thích: Claude Sonnet 4.6, Claude Opus 4.6, Claude Haiku 4.5