All Posts

Claude Code CLI Cheatsheet: Essential Commands and Shortcuts

You installed Claude Code, ran a few prompts, and got results. But you have a nagging feeling you are only using 20% of what the tool can do.

Claude Code CLI Cheatsheet: Essential Commands and Shortcuts

Published on
February 26, 2026

Overview

You installed Claude Code, ran a few prompts, and got results. But you have a nagging feeling you are only using 20% of what the tool can do. Somewhere between the basics and the advanced workflows, there is a layer of commands, flags, and shortcuts that separates casual usage from real productivity.

This cheatsheet compiles the essential Claude Code CLI commands and shortcuts that GTM engineers actually use day-to-day. Not the full documentation dump, but the commands worth committing to muscle memory: session management, context provision, file operations, MCP integration, and the keyboard shortcuts that save you from typing the same things repeatedly.

Bookmark this page. You will come back to it.

Core CLI Commands

These are the foundational commands you will use every time you open a terminal. If you have read our Claude Code for GTM automation guide, you have seen some of these in action. Here they are in one place.

Starting and Running Claude Code

The most basic operation: launching Claude Code and giving it something to do.

# Start an interactive session in the current directory
claude

# Start with an initial prompt
claude "explain the authentication flow in this project"

# Run a single command non-interactively (prints result to stdout)
claude -p "generate a docstring for utils/enrichment.py"

# Pipe input and run non-interactively
cat error.log | claude -p "explain what went wrong and suggest a fix"

# Continue the most recent conversation
claude --continue

# Resume a specific past session by ID
claude --resume SESSION_ID
Quick Tip

The -p (print) flag is essential for scripting. It runs Claude Code non-interactively, outputs the result to stdout, and exits. Use it to chain Claude Code into shell pipelines or cron jobs for hands-off automation pipelines.

Output and Formatting Flags

Control how Claude Code delivers results, especially useful when you are piping output into other tools or need machine-readable responses.

# Output in JSON format (useful for programmatic consumption)
claude -p --output-format json "list all API endpoints in this project"

# Stream JSON output in real-time
claude -p --output-format stream-json "refactor this function"

# Limit token usage for quick queries
claude --max-turns 3 "what does this function do"

Model and Configuration

Switch models or adjust behavior without modifying config files.

# Use a specific model
claude --model claude-sonnet-4-20250514

# Set a system prompt for the session
claude --system-prompt "You are a Python expert focused on API integrations"

# Add files to context on launch
claude --add-dir ./integrations --add-dir ./schemas

Session Management

Long-running projects mean long-running conversations. Knowing how to navigate, resume, and manage sessions prevents you from losing context or repeating yourself.

Listing and Resuming Sessions

# List recent sessions
claude sessions list

# Resume the last session (picks up right where you left off)
claude --continue

# Resume a specific session by ID
claude --resume abc123def456

In-Session Commands

Once inside an interactive session, these slash commands control the conversation flow.

CommandWhat It DoesWhen to Use It
/clearClears conversation historyWhen context gets stale or token usage is high
/compactSummarizes conversation to free up context windowLong sessions approaching token limits
/costShows token usage and estimated cost for the sessionMonitoring spend on complex tasks
/doctorRuns diagnostics on your Claude Code installationWhen things are not working as expected
/helpDisplays available slash commandsWhen you forget a command
/modelSwitch the model mid-sessionSwitch to a faster model for simple tasks
/permissionsView or update tool permissionsAdjusting what Claude Code can access
Session Persistence

Claude Code automatically saves your session history locally. If your terminal crashes or you accidentally close the window, use claude --continue to pick up exactly where you left off. No context is lost. This is especially valuable during multi-hour workflow builds where you are iterating on complex multi-system integrations.

Context Provision Commands

The quality of Claude Code's output is directly proportional to the quality of context you give it. This section covers every mechanism for feeding context into sessions, from project-level configuration to real-time file references.

CLAUDE.md: Your Project's Memory

The CLAUDE.md file is the single most impactful thing you can configure. Claude Code reads it at the start of every session, giving it persistent knowledge about your project.

# Where to place CLAUDE.md files (all are read, in order)
~/.claude/CLAUDE.md              # Global: applies to all projects
./CLAUDE.md                       # Project root: applies to this repo
./src/CLAUDE.md                   # Directory-level: applies in this subtree
./.claude/CLAUDE.local.md         # Local overrides (gitignored)

Claude Code reads CLAUDE.md files hierarchically. Global first, then project root, then the directory you are working in. This means you can set universal preferences globally (coding style, preferred languages) while keeping project-specific details in the repo.

CLAUDE.md Best Practice

Keep your project-level CLAUDE.md under 500 lines. Research shows AI models handle roughly 150-200 instructions reliably before quality degrades. Put the essentials in CLAUDE.md and reference detailed docs elsewhere: "For API authentication patterns, see docs/auth.md." Claude Code will read those files when it needs them.

Adding Context During a Session

Sometimes you need to point Claude Code at specific files or directories mid-conversation without restarting.

# Reference a file in your prompt (Claude Code reads it automatically)
"Look at integrations/hubspot.py and add retry logic matching that pattern to integrations/salesforce.py"

# Use @ syntax for file references in interactive mode
@integrations/hubspot.py add the same error handling to @integrations/salesforce.py

# Add an image for visual context (useful for debugging UI issues)
"Here is a screenshot of the error: @screenshot.png"

The init Command

If you are starting a new project or onboarding Claude Code to an existing codebase, the /init command generates a CLAUDE.md for you.

# Inside an interactive session
/init

This analyzes your project structure, detects frameworks and tools, and creates a starter CLAUDE.md. It is a good starting point, but you should always refine it with project-specific patterns and conventions. Teams building automation pipelines benefit from documenting their data schemas and API client patterns explicitly.

File and Code Operations

Claude Code's ability to read, write, and manipulate files is what separates it from chat-based AI assistants. Here are the patterns and commands for effective file operations.

Reading and Navigating Code

# Understand a specific file
"explain what integrations/clay.py does, focusing on the enrichment logic"

# Get a high-level project overview
"give me a summary of the project structure and how the modules connect"

# Search across the codebase
"find every place we handle rate limiting and list the approaches used"

# Analyze dependencies
"what external packages does this project use and are any outdated"

Writing and Editing Code

# Create a new file following existing patterns
"create a new integration client for Outreach following the pattern in integrations/hubspot.py"

# Refactor across multiple files
"rename the 'lead_score' field to 'qualification_score' everywhere in the codebase"

# Add functionality to existing code
"add pagination support to the Clay API client in integrations/clay.py"

# Generate boilerplate
"scaffold a new FastAPI endpoint for receiving Clay webhooks with proper validation"

Testing and Validation

# Write tests for existing code
"write unit tests for integrations/salesforce.py, mock all API calls"

# Run tests and fix failures
"run pytest and fix any failing tests"

# Add type hints
"add type annotations to all functions in transforms/lead_scoring.py"

# Lint and fix
"run ruff check and fix all issues"
The Iteration Loop

The most productive Claude Code workflow is: describe what you want, let it build, run tests, paste errors back. This write-test-fix cycle is where Claude Code excels. Instead of "write perfect code the first time," think "converge on working code through rapid iteration." Teams using this approach for CRM automation scripts report shipping integrations in hours instead of days.

Git Operations

Claude Code integrates directly with Git, handling version control without leaving the session.

# Create a feature branch
"create a branch called feature/outreach-webhook and switch to it"

# Stage and commit with a descriptive message
"commit these changes with a message describing what we built"

# Create a pull request (requires GitHub CLI)
"create a PR for this branch summarizing the changes"

# Review a diff
"show me what changed in the last 3 commits and flag anything concerning"

MCP Integration Commands

The Model Context Protocol lets Claude Code connect to external tools and data sources. If you are unfamiliar with MCP fundamentals, our MCP guide for GTM teams covers the architecture in depth. Here we focus on the practical commands for configuring and using MCP with Claude Code.

Configuring MCP Servers

MCP servers are configured in your Claude Code settings, either globally or per-project.

# Add an MCP server via CLI
claude mcp add my-server -e API_KEY=sk-xxx -- npx -y @example/mcp-server

# Add with specific scope (project-level only)
claude mcp add my-server --scope project -- python3 servers/my_server.py

# List configured MCP servers
claude mcp list

# Check server status and available tools
claude mcp get my-server

# Remove a server
claude mcp remove my-server

MCP Server Configuration File

For more complex setups, configure servers directly in the settings file.

# Project-level: .claude/settings.json
{
  "mcpServers": {
    "hubspot": {
      "command": "npx",
      "args": ["-y", "@hubspot/mcp-server"],
      "env": {
        "HUBSPOT_API_KEY": "your-key-here"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://localhost/gtm_data"
      }
    }
  }
}

Using MCP Tools in Conversation

Once configured, MCP tools are available to Claude Code just like its built-in capabilities. You do not need special syntax; just describe what you need.

# Query data through an MCP server
"pull the last 50 leads from our HubSpot and show me their lifecycle stages"

# Use MCP tools as part of a larger workflow
"check our Postgres database for leads missing company data,
then enrich them using the Clay MCP server"

# Combine MCP data with code generation
"query our analytics database for conversion rates by lead source,
then generate a Python report that visualizes the trends"
MCP Permission Model

Claude Code requires explicit permission the first time it uses a new MCP tool. You will see a prompt asking whether to allow the action. Use /permissions to manage which MCP tools are pre-approved, saving you from repeated confirmation prompts during complex workflows. For a step-by-step setup walkthrough, see our MCP server tutorial.

Productivity Shortcuts and Keyboard Commands

These shortcuts save seconds that compound into hours over a week of active use.

Keyboard Shortcuts (Interactive Mode)

ShortcutActionNotes
EscCancel current generationStops output mid-stream when you see the answer going off track
Esc (twice)Exit multi-line inputWhen you are composing a multi-line prompt and want to send it
TabAccept pending edit or tool actionApprove file writes or command execution quickly
Ctrl+CInterrupt and return to inputSofter than kill; keeps the session alive
Ctrl+DExit Claude CodeClean exit, session is saved automatically
Up arrowCycle through previous promptsReuse or edit earlier instructions

Multi-Line Input

For complex prompts that span multiple lines (common when describing multi-step workflows), use these approaches:

# Option 1: Backslash continuation
claude "Build a workflow that: \
  1. Pulls new leads from Clay hourly \
  2. Scores them against our ICP \
  3. Routes high-score leads to Outreach"

# Option 2: In interactive mode, just press Enter for a new line
# Claude Code waits for you to finish before processing

# Option 3: Pipe from a file for very complex instructions
cat prompts/enrichment-workflow.txt | claude -p

Permission Management Shortcuts

Claude Code asks for permission before executing potentially dangerous operations. Manage these approvals efficiently.

# Allow all file edits in a directory for this session
# (set via /permissions in interactive mode)

# Pre-approve specific tools in settings
# .claude/settings.json
{
  "permissions": {
    "allow": [
      "Read",
      "Write",
      "Bash(pytest:*)",
      "Bash(git:*)",
      "Bash(ruff:*)"
    ]
  }
}
Permission Strategy

Pre-approve safe, read-only operations and your standard development tools (test runners, linters, git). Keep approval required for network requests, package installs, and anything that modifies production systems. This balances speed with safety, which matters when building automated CRM workflows that touch live data.

Advanced Command Patterns

These patterns combine multiple Claude Code capabilities for more sophisticated workflows.

Shell Scripting with Claude Code

Use the non-interactive mode to integrate Claude Code into your existing automation scripts.

#!/bin/bash
# Automated code review on every PR

DIFF=$(git diff main...HEAD)
REVIEW=$(echo "$DIFF" | claude -p "Review this diff for bugs,
security issues, and style violations. Output as markdown.")
echo "$REVIEW" > review-output.md

# Post review as a PR comment (using gh CLI)
gh pr comment --body "$REVIEW"
#!/bin/bash
# Generate a daily enrichment report

claude -p --output-format json \
  "Query our analytics database for yesterday's enrichment stats.
   Return a JSON object with: total_processed, success_rate,
   top_failures, and average_processing_time." > daily-stats.json

Chaining Commands

Combine Claude Code with standard Unix tools for powerful pipelines.

# Find all TODO comments and generate implementation plans
grep -rn "TODO" src/ | claude -p "For each TODO, suggest an implementation approach"

# Analyze API response patterns
curl -s https://api.example.com/leads | claude -p "Analyze this JSON schema
and generate a Pydantic model"

# Generate documentation from code
find integrations/ -name "*.py" | xargs cat | claude -p \
  "Generate API documentation for these integration modules"

Headless Mode for CI/CD

Run Claude Code in automated environments where there is no interactive terminal.

# In a CI pipeline
claude -p --output-format json \
  --max-turns 5 \
  "Run the test suite and report results as JSON"

# Automated migration script
claude -p "Migrate all SQLAlchemy models from v1 to v2 syntax.
  Show me the changes before applying." --allowedTools "Read,Write"

Quick Reference Card

Print this section and keep it next to your monitor until the commands become automatic.

CategoryCommandPurpose
LaunchclaudeStart interactive session
claude "prompt"Start session with initial prompt
claude -p "prompt"Non-interactive, print and exit
Sessionclaude --continueResume last conversation
claude --resume IDResume specific session
/compactCompress context window
/clearReset conversation
/costCheck token usage
ContextCLAUDE.mdProject-level persistent context
/initAuto-generate CLAUDE.md
@filenameReference file in prompt
MCPclaude mcp addRegister MCP server
claude mcp listShow configured servers
claude mcp removeUnregister MCP server
Output--output-format jsonMachine-readable output
--output-format stream-jsonStreaming JSON
--max-turns NLimit agent iterations
KeysEscCancel generation
TabAccept action
Ctrl+CInterrupt (keep session)
Ctrl+DExit Claude Code

Beyond Individual Commands

Mastering Claude Code commands makes you faster as an individual. The harder problem shows up when your team has five people running Claude Code sessions, each with different CLAUDE.md files, different prompt patterns, and different mental models of your ICP, positioning, and competitive landscape.

Consider what happens when a GTM engineer uses Claude Code to generate outbound sequences. The output quality depends entirely on the context they provide: persona definitions, value propositions, competitive differentiators, proof points. If that context lives in scattered Google Docs, outdated Notion pages, or individual CLAUDE.md files, every team member gets slightly different results. Worse, when positioning changes, nobody updates all the sources.

What teams actually need is a shared context layer that any AI tool, including Claude Code, can query at runtime. Instead of hard-coding GTM knowledge into individual prompt files, you maintain a single source of truth that stays current and serves context to every tool in your stack.

This is exactly the problem that Octave's MCP server addresses. Rather than each engineer maintaining their own context files, Octave exposes your ICP definitions, persona pain points, competitive positioning, and proof points as MCP tools that Claude Code can query directly. A team member running claude "generate a cold email sequence for fintech CFOs" pulls live positioning from the same source of truth that feeds your sequence builders, research agents, and sales copilots. PMMs update positioning in one place; every AI tool reflects it immediately. No prompt archaeology, no version drift, no CLAUDE.md files going stale across fifteen repos.

FAQ

How do I check which version of Claude Code I am running?

Run claude --version in your terminal. To update to the latest version, run claude update or reinstall via the original installation method. Staying current matters because new commands and MCP capabilities are added regularly.

Can I use Claude Code without an internet connection?

No. Claude Code requires an active internet connection to communicate with Anthropic's API. Your code and files stay local, but the AI reasoning happens server-side. The session history is cached locally, so you can review previous conversations offline.

What is the difference between /clear and /compact?

/clear wipes the entire conversation history, starting fresh. /compact summarizes the existing conversation into a condensed form, preserving the key context while freeing up token budget. Use /compact when you want to keep working on the same task but are hitting context limits. Use /clear when you are switching to a completely different task.

How do I share Claude Code configurations across my team?

Commit your project-level CLAUDE.md and .claude/settings.json to version control. Use .claude/CLAUDE.local.md for personal overrides that should not be shared (this file should be in your .gitignore). For MCP server configurations that include API keys, use environment variables rather than hardcoded values.

Does Claude Code work with languages other than Python?

Yes. Claude Code is language-agnostic. It works effectively with Python, TypeScript, JavaScript, Go, Rust, and most other languages. For GTM automation specifically, Python and TypeScript are the most common, but Claude Code will match whatever language your project uses.

How do I control costs when running Claude Code extensively?

Use /cost regularly to monitor token consumption. Use /compact to reduce context size on long sessions. For scripted usage, set --max-turns to prevent runaway iterations. Consider using Sonnet for routine tasks and Opus for complex multi-step work. The non-interactive -p flag naturally limits costs by running single queries instead of open-ended sessions.

Conclusion

Claude Code's power comes from combining these commands fluently. The individual commands are simple. The leverage comes from knowing when to use --continue instead of starting a fresh session, when /compact saves a conversation that is hitting limits, and when to pipe output through -p --output-format json into your automation scripts.

Start by committing the quick reference card to memory. Then build habits around CLAUDE.md configuration and MCP server setup, because those are the force multipliers that compound over time. The commands in this cheatsheet are not just about working faster in a terminal. They are about building the muscle memory that lets you focus on the actual problem, whether that is qualifying leads at scale or wiring together your GTM stack, instead of wrestling with the tool itself.

FAQ

Frequently Asked Questions

Still have questions? Get connected to our support team.