cheat sheet

Claude Code CLI

All claude CLI flags, startup modes, non-interactive usage, environment variables, keyboard shortcuts, subcommands, exit codes, and configuration file locations in one place.

Claude Code CLI — Complete Command-Line Reference

What it is

Claude Code is Anthropic's official command-line AI coding assistant. The claude binary launches either an interactive REPL session or a one-shot non-interactive agent, both backed by the Anthropic API. It is distributed as an npm package (@anthropic-ai/claude-code) and runs on macOS, Linux, and Windows (native or WSL). The primary alternative for non-interactive use is the Anthropic API directly via curl or an SDK, but claude adds tool execution, project memory, hooks, MCP integration, and statusline UI on top of the raw API.

Install

Claude Code is installed globally via npm or the official installer.

bash
# npm (recommended)
npm install -g @anthropic-ai/claude-code

# Verify installation
claude --version

Output:

text
1.x.x
bash
# One-line installer (downloads the latest binary into ~/.local/bin)
curl -fsSL https://claude.ai/install.sh | bash

Output:

text
Downloading claude-code ...
Installed to /home/alice/.local/bin/claude

Invocation syntax

The claude command takes an optional prompt argument and a set of flags. With no arguments it opens an interactive REPL; with -p / --print it runs non-interactively and exits. There are also subcommands (mcp, sessions, login) that do not open a session.

bash
claude [OPTIONS] [PROMPT]
claude <SUBCOMMAND> [OPTIONS]

Output: (none — opens interactive session when run without -p)

Subcommands

SubcommandPurpose
claude loginOAuth flow for first-time auth
claude logoutClear stored credentials
claude mcp <action>Manage MCP servers — see MCP Servers
claude sessions <action>Manage saved sessions (list/resume/clear)
claude config <action>Show or edit settings
claude doctorEnvironment health check
claude updateSelf-update to the latest version
bash
claude doctor

Output:

text
✅ API key found (ANTHROPIC_API_KEY)
✅ Node.js 22.4.0
✅ @anthropic-ai/claude-code 1.x.x
✅ API connectivity: OK

Startup flags

These flags are passed on the command line when launching claude. Most can also be set persistently in settings.json or via environment variables.

FlagAliasDescription
--help-hShow help and exit
--version-vPrint version and exit
--print <prompt>-pNon-interactive: run prompt, print result, exit
--model <id>Override the model for this session
--api-key <key>Override the Anthropic API key for this session
--continue-cResume the most recent conversation
--resume <session-id>-rResume a specific saved conversation
--verboseEnable verbose/debug output
--no-ansiStrip ANSI color codes from output
--output-format <fmt>Output format: text (default), json, or stream-json
--max-turns <n>Limit agent turns in non-interactive mode
--system-prompt <text>-sReplace the default system prompt for this session
--append-system-prompt <text>Append text to the existing system prompt
--allowedTools <list>Comma-separated list of tools to permit
--disallowedTools <list>Comma-separated list of tools to block
--mcp-config <path>Path to an MCP server config file
--add-dir <path>Add a directory to the allowed filesystem scope (repeatable)
--no-auto-compactDisable automatic context compaction
--dangerously-skip-permissionsSkip all permission prompts (CI/automation use only)
--debugAlias for --verbose
bash
claude --version

Output:

text
1.x.x
bash
claude --help

Output:

text
claude [options] [prompt]

Options:
  -p, --print           Non-interactive mode: run prompt and exit
  -c, --continue        Resume the most recent conversation
  -r, --resume <id>     Resume a specific conversation
  --model <id>          Model to use
  --verbose             Enable verbose output
  --no-ansi             Disable color output
  ...

Non-interactive mode (-p / --print)

Non-interactive mode runs a single prompt, streams the response to stdout, and exits with code 0 on success. It is designed for shell scripts, CI pipelines, and editor integrations. Pipe stdin to provide file content as additional context.

bash
# Single prompt
claude -p "Explain what grep -P does"

Output:

text
The -P flag enables Perl-compatible regular expressions (PCRE) in grep,
allowing lookaheads, lookbehinds, and other Perl regex extensions that
the default POSIX regex engine does not support.
bash
# Pipe a file for context
cat src/main.py | claude -p "Review this for bugs and suggest fixes"

Output:

text
(analysis of the piped file content)
bash
# JSON output for scripting
claude -p "List three Linux process-inspection commands as JSON" --output-format json

Output:

text
{"type":"result","subtype":"success","result":"[\"ps\",\"top\",\"lsof\"]","is_error":false}
bash
# Stream JSON (one event per line, for real-time consumers)
claude -p "Write a haiku about bash" --output-format stream-json

Output:

text
{"type":"system","subtype":"init","session_id":"abc123",...}
{"type":"assistant","message":{"content":[{"type":"text","text":"Shell scripts run fast\n..."}]}}
{"type":"result","subtype":"success","result":"Shell scripts run fast\n...","is_error":false}
bash
# Limit agent turns (prevents runaway tool-use loops)
claude -p "Refactor the auth module" --max-turns 5

Output:

text
(runs up to 5 agent turns then stops)

Model selection

The model can be set per-session with --model, persistently in settings.json, or via the ANTHROPIC_MODEL environment variable. Use the full model ID.

bash
claude --model claude-opus-4-7
claude --model claude-sonnet-4-6
claude --model claude-haiku-4-5-20251001

Output: (none — opens interactive session with the specified model)

bash
# Non-interactive with model override
claude -p "Translate this to TypeScript" --model claude-haiku-4-5-20251001 < input.js

Output:

text
(TypeScript translation)

Session continuation

Claude Code persists conversations so you can resume a previous session. --continue reopens the most recent conversation in the current directory; --resume targets a specific session by ID.

bash
# Resume most recent conversation
claude --continue
claude -c

Output: (none — opens REPL with previous context loaded)

bash
# Resume a specific session
claude --resume abc123def456
claude -r abc123def456

Output: (none — opens REPL at the named session)

bash
# List sessions for this project
claude sessions list

Output:

text
sess_01abc... 2026-05-24 14:02  added JWT auth
sess_01def... 2026-05-23 10:18  refactor user service

Sessions are stored under ~/.claude/projects/<project-hash>/, keyed by the cwd's hash.

Tool permissions

Allow or block specific tools for a session. Tools are identified by name (e.g. Bash, Read, Edit, Write, WebSearch, WebFetch). Use --dangerously-skip-permissions in fully-automated CI contexts where no human is available to approve prompts.

bash
# Allow only read-only tools
claude --allowedTools "Read,Bash,WebSearch" -p "Find all TODO comments"

Output:

text
(search results — no file writes permitted)
bash
# Block specific tools
claude --disallowedTools "Write,Edit" -p "Review the codebase"

Output:

text
(review output — edit tools blocked)
bash
# Full automation (skip all prompts — use with caution)
claude --dangerously-skip-permissions -p "Run the test suite and fix failures"

Output:

text
(runs unattended — no permission prompts)

Bash subcommand patterns

Bash tool permissions support fine-grained subcommand patterns separated by colons:

bash
claude --allowedTools "Bash(npm test:npm run lint:git log:git diff:git status)" -p "..."

Output: (none — exits 0 on success)

System prompt override

Use --system-prompt to replace the default system prompt for a session. Use --append-system-prompt to add to the existing prompt without replacing it (almost always what you want).

bash
claude --system-prompt "You are a senior Go engineer. Answer only in Go idioms."

Output: (none — opens REPL with custom system prompt)

bash
claude -p "Write a hello-world server" \
  --append-system-prompt "Prefer the standard library net/http over third-party frameworks."

Output:

text
package main

import (
    "fmt"
    "net/http"
)
...

Environment variables

Environment variables provide a persistent alternative to CLI flags. They are read on every invocation and can be set in your shell profile or in a .env file.

VariableDescription
ANTHROPIC_API_KEYAnthropic API key (required unless set in settings)
ANTHROPIC_BASE_URLOverride API base URL (e.g. for a proxy)
ANTHROPIC_MODELDefault model ID
CLAUDE_CODE_MAX_OUTPUT_TOKENSOverride max output tokens
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFICSet to 1 to block telemetry/update checks
CLAUDE_CODE_USE_BEDROCKSet to 1 to use Amazon Bedrock
CLAUDE_CODE_USE_VERTEXSet to 1 to use Google Vertex AI
AWS_REGIONRequired when using Bedrock
ANTHROPIC_VERTEX_PROJECT_IDRequired when using Vertex
HTTP_PROXY / HTTPS_PROXYHTTP proxy for all outbound requests
NO_PROXYComma-separated hosts to bypass the proxy
BASH_DEFAULT_TIMEOUT_MSDefault Bash tool timeout in milliseconds
BASH_MAX_TIMEOUT_MSMaximum allowed Bash tool timeout
NO_COLORDisable ANSI color output
DISABLE_AUTOUPDATERSet to 1 to disable automatic updates
bash
export ANTHROPIC_API_KEY="sk-ant-..."
export ANTHROPIC_MODEL="claude-sonnet-4-6"
claude -p "What model are you using?"

Output:

text
I'm using claude-sonnet-4-6.
bash
# Route through a corporate proxy
export HTTPS_PROXY="http://proxy.myhost:3128"
claude -p "Fetch the homepage title of example.com"

Output:

text
The title is "Example Domain".

MCP server configuration

Model Context Protocol (MCP) servers extend Claude Code with additional tools. Pass a config file at startup or configure servers persistently in settings.json.

bash
# Load MCP config for a session
claude --mcp-config ./mcp-servers.json

Output: (none — opens REPL with MCP tools available)

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/alice"]
    }
  }
}

Output: (none — JSON config file, not a command)

Keyboard shortcuts

These key bindings work in the interactive REPL.

KeyAction
EnterSubmit the current message
Shift+EnterInsert a newline without submitting
Ctrl+CCancel the current in-progress operation
Ctrl+DExit the session (equivalent to /exit)
Ctrl+LClear the terminal screen
Ctrl+RReverse-search prompt history
/ Navigate prompt history
TabAutocomplete slash commands and file paths
EscapeCancel autocomplete / dismiss suggestion
bash
# Start interactive session and use keyboard shortcuts
claude

Output: (none — interactive REPL starts)

Configuration files

Claude Code reads configuration from several files in priority order (highest first).

FileScopeDescription
.claude/settings.local.jsonProject (gitignored)Personal overrides
.claude/settings.jsonProjectProject-level settings, hooks, permissions
~/.claude/settings.jsonUserGlobal user-level settings
~/.claude/CLAUDE.mdUserGlobal memory injected into every session
.claude/CLAUDE.md or <project>/CLAUDE.mdProjectProject-level memory (checked into git)
.claude/commands/*.mdProjectCustom slash commands
~/.claude/commands/*.mdUserPersonal slash commands
.claude/skills/<name>/SKILL.mdProjectProject-scoped custom skills
~/.claude/skills/<name>/SKILL.mdUserPersonal custom skills
bash
# Print the active settings (merged view)
claude --print "show me the model you are using and the active settings"

Output:

text
I'm using claude-sonnet-4-6. The active settings merge your project
.claude/settings.json with your user ~/.claude/settings.json.
bash
# Open settings file in editor via slash command (in REPL)
# /config

Output: (none — opens settings.json in $EDITOR)

Output format reference

FormatFlag valueDescription
TexttextDefault — plain text streamed to stdout
JSONjsonSingle JSON object printed after completion
Stream JSONstream-jsonNewline-delimited JSON events as they arrive
bash
# Capture JSON result in a shell variable
result=$(claude -p "Sum 2 + 2" --output-format json)
echo "$result" | jq -r '.result'

Output:

text
4

JSON result schema

The json output format returns a single object with these fields:

FieldTypeDescription
typestringAlways "result"
subtypestring"success" or "error"
resultstringThe assistant's final text response
session_idstringSession ID for this run
is_errorbooleantrue if any tool call errored
cost_usdnumberEstimated cost in USD
duration_msnumberTotal wall-clock duration
num_turnsnumberAgent turns used
bash
claude -p "What is 2+2?" --output-format json | jq

Output:

text
{
  "type": "result",
  "subtype": "success",
  "result": "4",
  "session_id": "sess_01abc...",
  "is_error": false,
  "cost_usd": 0.0008,
  "duration_ms": 1240,
  "num_turns": 1
}

Stream JSON event types

Each line in stream-json mode is one event:

TypeDescription
system.initSession start; carries session_id, model, tools
assistant.messageAssistant message (may contain text or tool_use blocks)
user.messageTool result message from the harness
resultFinal result, same shape as json output
errorError mid-stream

Exit codes

Exit codeMeaning
0Success
1Generic error (auth, network, unknown flag)
2Tool execution failed mid-task
3Agent hit --max-turns without finishing
4User cancelled (Ctrl+C)
5Hook blocked the operation
bash
claude -p "test" --max-turns 1
echo "exit=$?"

Output:

text
(response truncated by max-turns)
exit=3

Common pitfalls

  1. Missing API key — if ANTHROPIC_API_KEY is not set and not in settings.json, claude exits with an auth error; set the key in your shell profile.
  2. --max-turns in interactive mode--max-turns only applies to -p non-interactive mode; in the REPL it has no effect.
  3. --dangerously-skip-permissions in shared environments — never use this flag on a shared machine; it disables all permission prompts and allows unrestricted tool execution.
  4. Model ID typos — Claude Code validates model IDs on startup; an unknown ID causes an immediate error. Use claude --version and check the current model list if unsure.
  5. --system-prompt replaces, not appends — if you want to extend the default system prompt, use --append-system-prompt instead; --system-prompt replaces the entire system prompt.
  6. Session IDs are project-scoped — session IDs stored under ~/.claude/projects/<hash>/ are keyed to the working directory; switching directories changes the active project and its session history.
  7. --add-dir repeats, not concatenates — to add multiple directories pass --add-dir multiple times, not a comma-separated string.
  8. stream-json without a parser — piping stream-json to a script that expects whole JSON breaks; use jq -c . or a line-oriented JSON reader.

Real-world recipes

Automated code review in CI

Run a non-interactive review on every pull request diff without any interactive prompts.

bash
git diff origin/main...HEAD | claude \
  --dangerously-skip-permissions \
  --output-format json \
  -p "Review this diff. List any bugs, security issues, or style violations as JSON." \
  | jq -r '.result'

Output:

text
[
  {"severity":"warning","file":"src/auth.py","line":42,"issue":"Hardcoded timeout value"},
  {"severity":"error","file":"src/db.py","line":17,"issue":"SQL query is not parameterized"}
]

Batch-process files

Apply a transformation to every file matching a pattern using non-interactive mode.

bash
for f in src/**/*.ts; do
  echo "=== $f ===" 
  claude -p "Add JSDoc comments to all exported functions in this file" < "$f" > "${f}.tmp"
  mv "${f}.tmp" "$f"
done

Output:

text
=== src/auth.ts ===
=== src/db.ts ===

Switch model mid-session with /model

text
> /model claude-opus-4-7

Output:

text
Active model is now claude-opus-4-7.

Custom system prompt for a project

Set a project-specific system prompt in .claude/settings.json so every session automatically uses it.

json
{
  "appendSystemPrompt": "You are working in a Python 3.12 Django 5 project. Always use type hints. Prefer class-based views.",
  "model": "claude-sonnet-4-6"
}

Output: (none — JSON config file applied on next claude launch)

Headless with bounded cost

Cap a non-interactive job to a few turns and a known model to keep cost predictable.

bash
claude -p "Summarise the last week of commits" \
  --model claude-haiku-4-5-20251001 \
  --max-turns 3 \
  --allowedTools "Bash(git log:git show)" \
  --output-format json | jq '.cost_usd'

Output:

text
0.0034

Multi-directory workspace

Open Claude with access to multiple project roots — useful when refactoring shared code across sibling repos.

bash
cd ~/Code/frontend
claude --add-dir ~/Code/backend --add-dir ~/Code/shared

Output: (none — opens REPL with extended filesystem scope)

Wrap claude in a tmux session-monitor

bash
tmux new-session -d -s claude-monitor \
  'while true; do claude -p "Check the build status of main" --output-format json; sleep 600; done'

Output: (none — background loop, check with tmux attach -t claude-monitor)