Làm chủ Claude Code trong một tuần (Phần 5): CLI Reference

· 8 min read

Đây là phần thứ năm trong series "Làm chủ Claude Code trong một tuần". Trong bài này, chúng ta sẽ tìm hiểu CLI Reference — cách sử dụng Claude Code từ command line.

CLI là gì?

Claude Code CLI cho phép bạn chạy Claude Code từ terminal thay vì chỉ qua VS Code. Điều này mở ra khả năng automation, scripting, và tích hợp vào CI/CD pipelines.

┌────────────────────────────────────────────────────────────┐
│                    CLAUDE CODE CLI                          │
├────────────────────────────────────────────────────────────┤
│                                                             │
│   Interactive Mode          Print Mode           Pipe Mode │
│   ┌─────────────┐          ┌──────────┐        ┌─────────┐│
│   │ $ claude    │          │ $ claude │        │ cat f | ││
│   │ > chat...   │          │   -p ... │        │ claude  ││
│   │ > chat...   │          │          │        │   -p ..││
│   └─────────────┘          └──────────┘        └─────────┘│
│                                                             │
│   Use case:                Use case:           Use case:   │
│   Development              Scripts             Processing  │
│   Exploration              CI/CD               Log analysis│
│                                                             │
└────────────────────────────────────────────────────────────┘

Basic Usage

Interactive Mode (Default)

# Start interactive session
claude

# With initial prompt
claude "explain this project"

# In specific directory
cd /path/to/project && claude
# Run once and exit
claude -p "review this code"

# Output result only (no streaming)
claude -p --output-format json "list all functions"

Pipe Mode

# Pipe content to Claude
cat error.log | claude -p "explain this error"

# Process file
cat src/service.ts | claude -p "refactor to use async/await"

# Combine with other commands
git diff | claude -p "write commit message"

CLI Flags & Options

Core Flags

Flag Short Description
--print -p Non-interactive mode
--output-format Output format: text, json, stream-json
--resume -r Resume session by name
--continue -c Continue most recent session
--model -m Specify model
--system-prompt Custom system prompt
--max-turns Limit conversation turns
--verbose -v Verbose output

Permission Flags

Flag Description
--dangerously-skip-permissions Skip all permission prompts
--allowedTools Whitelist specific tools
--disallowedTools Blacklist specific tools

Session Flags

Flag Description
--resume <name> Resume named session
--continue Continue last session
--fork Fork current session

Practical Examples

1. Code Review trong CI/CD

#!/bin/bash
# ci-review.sh

# Get changed files
CHANGED_FILES=$(git diff --name-only origin/main...HEAD)

# Review each file
for file in $CHANGED_FILES; do
    echo "Reviewing: $file"
    cat "$file" | claude -p "
    Review this code for:
    - Security vulnerabilities
    - Performance issues
    - Code style violations
    Return JSON format:
    {
        \"issues\": [...],
        \"severity\": \"low|medium|high\",
        \"suggestions\": [...]
    }
    " --output-format json >> review-results.json
done

2. Generate Commit Messages

# git-commit-ai.sh

# Get staged changes
DIFF=$(git diff --cached)

# Generate commit message
MESSAGE=$(echo "$DIFF" | claude -p "
Generate a conventional commit message for these changes.
Format: type(scope): description

Types: feat, fix, docs, style, refactor, test, chore

Return only the commit message, nothing else.
")

# Commit with generated message
git commit -m "$MESSAGE"

3. Error Log Analysis

# analyze-logs.sh

# Get recent errors
ERRORS=$(tail -100 /var/log/app/error.log)

# Analyze
echo "$ERRORS" | claude -p "
Analyze these error logs:
1. Group similar errors
2. Identify root causes
3. Suggest fixes
4. Priority: high, medium, low

Output format:
## Summary
## Grouped Errors
## Root Causes
## Recommended Actions
"

4. Documentation Generation

# generate-docs.sh

# Find all PHP files
find app -name "*.php" -type f | while read file; do
    # Generate documentation
    cat "$file" | claude -p "
    Generate technical documentation for this PHP file.
    Include:
    - Purpose
    - Classes/Methods
    - Parameters
    - Return values
    - Usage examples
    
    Format: Markdown
    " > "docs/$(basename $file .php).md"
done

5. Test Generation

# generate-tests.sh

# Target file
FILE=$1

# Generate tests
cat "$FILE" | claude -p "
Generate PHPUnit tests for this class.
- Cover all public methods
- Include edge cases
- Use data providers where appropriate
- Follow Arrange-Act-Assert pattern
" > "tests/$(basename $FILE .php)Test.php"

Session Management

Name Sessions

# Start named session
claude -r "feature-auth" "implement user authentication"

# Later, resume
claude -r "feature-auth" "continue with password reset"

Continue Last Session

# Continue where you left off
claude -c "add the validation we discussed"

Fork Session

# Fork to try alternative approach
claude --fork "try using OAuth instead"

List Sessions

# List all sessions
claude sessions list

# Output:
# NAME              LAST ACTIVE         TURNS
# feature-auth      2 hours ago         15
# refactor-api      1 day ago           42
# debug-payment     3 days ago          8

Output Formats

Text (Default)

claude -p "explain this code"
# Output: Plain text explanation

JSON

claude -p --output-format json "list functions in this file"

# Output:
{
    "functions": [
        {"name": "handleRequest", "line": 15},
        {"name": "validateInput", "line": 42}
    ]
}

Stream JSON

claude -p --output-format stream-json "explain step by step"

# Output: NDJSON (newline-delimited JSON)
{"type": "thinking", "content": "Analyzing..."}
{"type": "text", "content": "Step 1: ..."}
{"type": "text", "content": "Step 2: ..."}
{"type": "done"}

CI/CD Integration

GitHub Actions

# .github/workflows/ai-review.yml
name: AI Code Review

on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - name: Install Claude Code
        run: npm install -g @anthropic/claude-code
      
      - name: Set API Key
        run: echo "ANTHROPIC_API_KEY=${{ secrets.ANTHROPIC_API_KEY }}" >> $GITHUB_ENV
      
      - name: Review Changes
        run: |
          git diff origin/main...HEAD | claude -p "
          Review these changes for:
          - Security issues
          - Performance problems
          - Code style
          
          Format as GitHub PR comment markdown.
          " > review.md
      
      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('review.md', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: review
            });

GitLab CI

# .gitlab-ci.yml
ai-review:
  stage: review
  image: node:20
  script:
    - npm install -g @anthropic/claude-code
    - git diff origin/main...HEAD | claude -p "review code" > review.md
    - cat review.md
  artifacts:
    paths:
      - review.md

Pre-commit Hook

#!/bin/bash
# .git/hooks/pre-commit

# Get staged changes
DIFF=$(git diff --cached)

# Check for issues
ISSUES=$(echo "$DIFF" | claude -p "
Check for:
1. Hardcoded credentials
2. Debug statements (console.log, dd(), var_dump())
3. TODO comments with no issue reference

Return JSON: {\"hasIssues\": true/false, \"issues\": [...]}
" --output-format json)

# Parse result
HAS_ISSUES=$(echo "$ISSUES" | jq -r '.hasIssues')

if [ "$HAS_ISSUES" = "true" ]; then
    echo "⚠️  Issues found:"
    echo "$ISSUES" | jq -r '.issues[]'
    exit 1
fi

exit 0

Headless Mode

Chạy Claude Code hoàn toàn tự động trong CI:

# Headless mode - no permission prompts
claude -p "run tests and generate report" \
    --dangerously-skip-permissions \
    --max-turns 10 \
    --output-format json

Permission Modes

Mode Behavior
default Ask for permissions
acceptEdits Auto-accept file edits
plan Planning mode only
dontAsk Execute without asking
bypassPermissions Skip all permission checks
# Accept all edits automatically
CLAUDE_PERMISSION_MODE=acceptEdits claude "fix all lint errors"

# Planning mode only (no execution)
CLAUDE_PERMISSION_MODE=plan claude "how would you refactor this?"

Scripting Best Practices

1. Use JSON output for parsing

# Bad - parsing text output
RESULT=$(claude -p "list files")
# Difficult to parse reliably

# Good - use JSON
RESULT=$(claude -p "list files as JSON array" --output-format json)
FILES=$(echo "$RESULT" | jq -r '.files[]')

2. Handle errors

# Check exit code
if ! claude -p "check for issues" --output-format json > result.json; then
    echo "Claude Code failed"
    exit 1
fi

# Validate JSON output
if ! jq empty result.json 2>/dev/null; then
    echo "Invalid JSON output"
    exit 1
fi

3. Set timeouts

# Set timeout for long operations
timeout 300 claude -p "analyze entire codebase"

4. Limit context

# Only send relevant parts
head -100 largefile.log | claude -p "analyze errors"

# Or use grep first
grep "ERROR" app.log | tail -50 | claude -p "explain these errors"

Environment Variables

Variable Description
ANTHROPIC_API_KEY API key
CLAUDE_CODE_MODEL Default model
CLAUDE_PERMISSION_MODE Permission mode
CLAUDE_CODE_DEBUG Enable debug output
# Set in .bashrc or .zshrc
export ANTHROPIC_API_KEY="sk-ant-..."
export CLAUDE_CODE_MODEL="claude-sonnet-4"

Useful Scripts

Quick Code Explanation

# Add to .bashrc
explain() {
    cat "$1" | claude -p "Explain this code concisely"
}

# Usage
explain src/services/AuthService.php

Quick Fix

# Add to .bashrc
aifix() {
    local file=$1
    local issue=$2
    cat "$file" | claude -p "Fix: $issue. Return only the fixed code." > "${file}.fixed"
    mv "${file}.fixed" "$file"
}

# Usage
aifix src/api.ts "handle null responses"

Generate .gitignore

# Add to .bashrc
gitignore() {
    local lang=$1
    claude -p "Generate .gitignore for $lang project. Return only the file content." > .gitignore
}

# Usage
gitignore "laravel"

Tổng kết

CLI mở ra nhiều khả năng automation:

  • ✅ Non-interactive mode cho scripts
  • ✅ Pipe input từ other commands
  • ✅ JSON output cho parsing
  • ✅ Session management
  • ✅ CI/CD integration

Tiếp theo

Trong phần tiếp theo, chúng ta sẽ tìm hiểu Skills — cách tạo khả năng tái sử dụng được tự động kích hoạt khi relevant.

Tài liệu tham khảo


Series này được dịch và mở rộng từ claude-howto — MIT License.

Bình luận