AI logoAIv2.1BEGINNER

Claude Code

Claude Code cheat sheet covering CLI commands, configuration options, slash commands, and practical usage examples for AI-assisted coding.

10 min read
aicliautomationproductivity

Sign in to mark items as known and track your progress.

Sign in

Installation & Setup

Getting started with Claude Code

Installation Methods

Multiple ways to install Claude Code

📄 Codebash
# NPM Installation (recommended)
npm install -g @anthropic-ai/claude-code

# Native Installer (macOS/Linux/WSL)
curl -fsSL claude.ai/install.sh | bash

# Windows PowerShell
irm https://claude.ai/install.ps1 | iex

# Verify installation
claude --version

# Requirements: Node.js 18+
💡 NPM installation is recommended for most users
📌 Native installers available for all platforms
⚡ Requires Node.js 18 or newer
installation

Basic Usage

Starting and using Claude Code

📄 Codebash
# Start interactive session
claude

# Run one-time task
claude "refactor this function to use async/await"

# Continue most recent conversation
claude -c
claude --continue

# Resume and pick previous conversation
claude -r
claude --resume

# Non-interactive mode
claude --print "explain this codebase"

# Start in Plan Mode
claude --permission-mode plan

# Create a Git commit (ask in a session, or use the /commit slash command)
claude "commit my staged changes with a conventional message"
📄 Examplebash
// EXAMPLE: Refactoring a callback to async/await
$ claude "refactor this callback to use async/await"

// EXAMPLE: Continuing previous work
$ claude -c
> "Let's add error handling to that function"

// EXAMPLE: Creating a commit
$ claude commit
> Claude analyzes changes and creates commit message
📌 Interactive mode is the default
📌 Use quotes for one-time tasks
🔍 Can resume previous conversations
basics

Essential Commands

Core slash commands in Claude Code

Session Management

Control your Claude Code session

📄 Codebash
# Authentication
/login          # Log in to your account
/logout         # Sign out completely

# Session control
/exit           # Exit Claude Code (also: exit, Ctrl+C)
/clear          # Clear conversation history
/help           # Show available commands

# Context management
/compact        # Reduce context size when near limit
📄 Examplebash
// EXAMPLE: Managing a long session
> "Help me build a REST API"
[... extensive work ...]
> /compact  // Reduce context when getting full
> "Now add authentication"

// EXAMPLE: Starting fresh
> /clear
> "Let's work on a different feature"
📌 Use /clear to start fresh
📌 /compact helps with long sessions
📌 Multiple ways to exit
commandssession

Configuration Commands

Customize Claude Code behavior

📄 Codebash
# Configuration access
/config         # Open configuration menu
/permissions    # Allow tools to run without approval
/hooks          # Configure hooks
/output-style   # Access output styles menu

# Output styles
/output-style:new  # Create new output style

# Advanced
/agents         # List available subagents
/doctor         # Check installation health
/bug            # Report issues to Anthropic
📌 /config opens interactive menu
📌 Permissions control tool approval
📌 Create custom output styles
commandsconfig

Custom Commands

Create your own slash commands

📄 Codemarkdown
# Custom command locations:
~/.claude/commands/     # User-level commands
.claude/commands/       # Project-level commands

# Example: optimize.md
---
name: optimize
description: Optimize performance
---
Find and optimize performance bottlenecks

# Example with arguments: fix-issue.md
---
name: fix-issue
description: Fix GitHub issue
---
Fix issue #$ARGUMENTS from our GitHub repo

# Use custom commands:
/optimize
/fix-issue 123
📄 Examplemarkdown
// EXAMPLE: Creating a test runner command
// File: ~/.claude/commands/test.md
---
name: test
description: Run tests for a specific file
---
Run the test suite for $ARGUMENTS and fix any failures

// Usage:
> /test auth.service.ts
📌 Commands are markdown files
🔍 Support arguments with $ARGUMENTS
📌 Project commands override user commands
customcommands

Configuration Files

Understanding Claude Code configuration

Settings Files

Configuration file hierarchy

📄 Codebash
# User-level settings
~/.claude/settings.json         # Global configuration
~/.claude.json                  # User state (projects, MCP, etc.)
~/.claude/.credentials.json     # Auth token (macOS uses Keychain)

# Project-level settings
.claude/settings.json       # Project configuration
.claude/settings.local.json # Local overrides (gitignored)
CLAUDE.md                   # Project instructions

# Directory structure
.claude/
├── settings.json          # Project config
├── settings.local.json    # Local overrides
├── commands/              # Custom commands
├── agents/                # Custom subagents
├── output-styles/         # Custom styles
└── hooks/                 # Hook scripts
📌 Project settings override user settings
📌 Use settings.local.json for personal config
📌 CLAUDE.md for project-specific instructions
configfiles

Permissions Configuration

Control tool approval requirements

📄 Codejson
# .claude/settings.json
{
  "permissions": {
    "defaultMode": "acceptEdits"  // default | acceptEdits | plan | bypassPermissions
  }
}

# Permission modes:
# default           - Standard prompting; asks before sensitive actions
# acceptEdits       - Auto-accept file edits, still prompt for other tools
# plan              - Read-only planning mode, no writes/execution
# bypassPermissions - Skip all permission prompts (use with caution)

# Per-tool permissions via /permissions command:
/permissions
# Then select tools to auto-approve
📌 plan mode is read-only and safest for review
📌 acceptEdits auto-accepts file edits for trusted work
🔍 Can set per-tool permissions
permissionsconfig

CLAUDE.md File

Project-specific instructions

📄 Codemarkdown
# Create CLAUDE.md in project root
# Example content:

# Project Overview
This is a Next.js e-commerce application...

## Code Style
- Use TypeScript strict mode
- Prefer async/await over callbacks
- Follow ESLint configuration

## Important Notes
- Never modify the payments module
- Always run tests before committing
- Use pnpm instead of npm

## Architecture
/src/api - API routes
/src/components - React components
/src/lib - Utility functions
📌 Claude reads this for project context
📌 Include coding standards and patterns
📌 Document important constraints
documentation

Output Styles

Customize Claude Code responses

Built-in Styles

Available output styles

📄 Codebash
# Access output styles menu
/output-style

# Built-in styles:
- Default      # Standard Claude Code behavior
- Explanatory  # More detailed explanations
- Learning     # Educational, step-by-step

# Switch styles during session:
/output-style
# Select from menu

# Create new style:
/output-style:new
📌 Switch styles anytime
📌 Explanatory for learning
📌 Learning for tutorials
styles

Custom Output Styles

Create your own response styles

📄 Codemarkdown
# Location: ~/.claude/output-styles/concise.md
---
name: Concise
description: Brief, to-the-point responses
---

You are a concise coding assistant.
- Give brief explanations
- Minimize commentary
- Focus on code solutions
- Use bullet points for clarity

# Location: .claude/output-styles/verbose.md
---
name: Verbose
description: Detailed explanations
---

Provide comprehensive explanations:
- Explain reasoning behind decisions
- Include alternative approaches
- Add detailed comments in code
- Discuss trade-offs
📄 Examplemarkdown
// EXAMPLE: Creating a "Security Focus" style
// File: ~/.claude/output-styles/security.md
---
name: Security Focus
description: Emphasize security considerations
---

Always consider security implications:
- Check for SQL injection vulnerabilities
- Validate all user inputs
- Never log sensitive data
- Use environment variables for secrets
📌 Markdown files with frontmatter
📌 User styles in ~/.claude/output-styles/
📌 Project styles in .claude/output-styles/
customstyles

Hooks System

Automate and customize behavior

Hook Events

Available hook trigger points

📄 Codebash
# Hook events:
PreToolUse       # Before tool execution
PostToolUse      # After tool execution
UserPromptSubmit # When user sends message
Notification     # System notifications
Stop             # When stopping execution
SubagentStop     # When subagent stops
PreCompact       # Before context compaction
SessionStart     # Session begins
SessionEnd       # Session ends

# Configure via:
/hooks           # Interactive configuration
# Or edit ~/.claude/settings.json directly
📌 Hooks run at specific events
🔍 Can run commands or scripts
📌 Useful for logging and automation
hooks

Hook Configuration

Setting up hooks in settings.json

📄 Codejson
# ~/.claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '\"Running: \" + .tool_input.command' >> ~/.claude/log.txt"
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/validate_prompt.py"
          }
        ]
      }
    ]
  }
}
📄 Examplejson
// EXAMPLE: Log all bash commands
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "date >> ~/.claude/bash.log && echo '{{tool_input.command}}' >> ~/.claude/bash.log"
      }]
    }]
  }
}
📌 Matcher filters by tool name
🔍 Can run commands or scripts
📌 Access tool data via placeholders
hooksconfig

Hook Scripts

Creating custom hook scripts

📄 Codepython
#!/usr/bin/env python3
# ~/.claude/hooks/log_commands.py

import sys
import json
from datetime import datetime

# Read input from stdin
data = json.loads(sys.stdin.read())

# Log command details
with open('command_log.txt', 'a') as f:
    f.write(f"{datetime.now()}: {data['tool_input']['command']}\n")

# Return 0 to allow, non-zero to block
sys.exit(0)

# Make executable:
chmod +x ~/.claude/hooks/log_commands.py
📌 Scripts receive JSON via stdin
📌 Return 0 to allow, non-zero to block
🔍 Can modify or validate actions
hooksscripts

Advanced Features

Power user capabilities

Subagents

Specialized agents for complex tasks

📄 Codemarkdown
# List available subagents
/agents

# Built-in subagents:
- general-purpose  # General tasks
- statusline-setup # Configure status line
- output-style-setup # Create output styles

# Custom subagent: .claude/agents/tester.md
---
name: tester
description: Run comprehensive tests
tools: Bash, Read, Write
---
Run all test suites and fix any failures

# Subagents enable:
- Parallel processing
- Specialized workflows
- Complex multi-step operations
📄 Examplemarkdown
// EXAMPLE: Complex refactoring with subagents
> "Refactor the entire authentication system to use OAuth"

Claude: I'll use multiple subagents for this:
- Agent 1: Update database schema
- Agent 2: Refactor backend API
- Agent 3: Update frontend components
- Agent 4: Update tests
[Agents work in parallel]
📌 Subagents handle specific tasks
🔍 Can work in parallel
📌 Define custom agents in .claude/agents/
agentsadvanced

MCP Integration

Model Context Protocol for external data

📄 Codejson
# MCP enables access to:
- Databases
- APIs  
- Documentation
- External tools

# Configuration in .mcp.json at the project root:
{
  "mcpServers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://..."]
    }
  }
}

# Or add one from the CLI: claude mcp add

# Then in Claude:
"Query the users table for active accounts"
"Check the API documentation for endpoints"
📌 Connect external data sources
📌 Extends Claude capabilities
⚡ Requires MCP server setup
mcpintegration

CI/CD Integration

Use Claude Code in automation

📄 Codeyaml
# GitHub Actions example
name: Claude Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: npm install -g @anthropic-ai/claude-code
      - run: |
          claude --print "Review this PR and suggest improvements" > review.md
          
# GitLab CI example
claude-review:
  script:
    - npm install -g @anthropic-ai/claude-code
    - claude --print "Check for security issues"
    
# Pre-commit hook
#!/bin/bash
claude --print "Review staged changes for issues"
📌 Integrate with any CI/CD system
📌 Use --print for non-interactive mode
📌 Automate code reviews and checks
cicdautomation

Troubleshooting

Common issues and solutions

Diagnostic Commands

Debug and fix issues

📄 Codebash
# Check installation health
/doctor

# Report bugs to Anthropic
/bug

# Environment variables for debugging
USE_BUILTIN_RIPGREP=0  # Disable built-in ripgrep

# Common fixes:
# Permission denied
sudo npm install -g @anthropic-ai/claude-code

# Command not found
export PATH="$PATH:~/.local/bin"

# WSL issues
# Check .wslconfig for proper settings
📌 /doctor checks configuration
📌 /bug sends reports to Anthropic
📌 Check PATH for command issues
troubleshooting

Context Management

Handle context size limits

📄 Codebash
# When hitting context limits:

# 1. Use /compact command
/compact
# Reduces context while preserving important info

# 2. Clear and start fresh
/clear
# Completely resets conversation

# 3. Use focused requests
# Instead of: "Fix all the issues"
# Use: "Fix the TypeScript error in auth.ts"

# 4. Break large tasks
# Split into smaller, focused sessions
📌 /compact preserves key context
📌 Break large tasks into steps
📌 Be specific to reduce context usage
contexttips