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.
# npm (recommended)
npm install -g @anthropic-ai/claude-code
# Verify installation
claude --version
Output:
1.x.x
# One-line installer (downloads the latest binary into ~/.local/bin)
curl -fsSL https://claude.ai/install.sh | bash
Output:
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.
claude [OPTIONS] [PROMPT]
claude <SUBCOMMAND> [OPTIONS]
Output: (none — opens interactive session when run without -p)
Subcommands
| Subcommand | Purpose |
|---|---|
claude login | OAuth flow for first-time auth |
claude logout | Clear 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 doctor | Environment health check |
claude update | Self-update to the latest version |
claude doctor
Output:
✅ 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.
| Flag | Alias | Description |
|---|---|---|
--help | -h | Show help and exit |
--version | -v | Print version and exit |
--print <prompt> | -p | Non-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 | -c | Resume the most recent conversation |
--resume <session-id> | -r | Resume a specific saved conversation |
--verbose | Enable verbose/debug output | |
--no-ansi | Strip 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> | -s | Replace 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-compact | Disable automatic context compaction | |
--dangerously-skip-permissions | Skip all permission prompts (CI/automation use only) | |
--debug | Alias for --verbose |
claude --version
Output:
1.x.x
claude --help
Output:
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.
# Single prompt
claude -p "Explain what grep -P does"
Output:
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.
# Pipe a file for context
cat src/main.py | claude -p "Review this for bugs and suggest fixes"
Output:
(analysis of the piped file content)
# JSON output for scripting
claude -p "List three Linux process-inspection commands as JSON" --output-format json
Output:
{"type":"result","subtype":"success","result":"[\"ps\",\"top\",\"lsof\"]","is_error":false}
# Stream JSON (one event per line, for real-time consumers)
claude -p "Write a haiku about bash" --output-format stream-json
Output:
{"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}
# Limit agent turns (prevents runaway tool-use loops)
claude -p "Refactor the auth module" --max-turns 5
Output:
(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.
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)
# Non-interactive with model override
claude -p "Translate this to TypeScript" --model claude-haiku-4-5-20251001 < input.js
Output:
(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.
# Resume most recent conversation
claude --continue
claude -c
Output: (none — opens REPL with previous context loaded)
# Resume a specific session
claude --resume abc123def456
claude -r abc123def456
Output: (none — opens REPL at the named session)
# List sessions for this project
claude sessions list
Output:
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.
# Allow only read-only tools
claude --allowedTools "Read,Bash,WebSearch" -p "Find all TODO comments"
Output:
(search results — no file writes permitted)
# Block specific tools
claude --disallowedTools "Write,Edit" -p "Review the codebase"
Output:
(review output — edit tools blocked)
# Full automation (skip all prompts — use with caution)
claude --dangerously-skip-permissions -p "Run the test suite and fix failures"
Output:
(runs unattended — no permission prompts)
Bash subcommand patterns
Bash tool permissions support fine-grained subcommand patterns separated by colons:
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).
claude --system-prompt "You are a senior Go engineer. Answer only in Go idioms."
Output: (none — opens REPL with custom system prompt)
claude -p "Write a hello-world server" \
--append-system-prompt "Prefer the standard library net/http over third-party frameworks."
Output:
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.
| Variable | Description |
|---|---|
ANTHROPIC_API_KEY | Anthropic API key (required unless set in settings) |
ANTHROPIC_BASE_URL | Override API base URL (e.g. for a proxy) |
ANTHROPIC_MODEL | Default model ID |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | Override max output tokens |
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC | Set to 1 to block telemetry/update checks |
CLAUDE_CODE_USE_BEDROCK | Set to 1 to use Amazon Bedrock |
CLAUDE_CODE_USE_VERTEX | Set to 1 to use Google Vertex AI |
AWS_REGION | Required when using Bedrock |
ANTHROPIC_VERTEX_PROJECT_ID | Required when using Vertex |
HTTP_PROXY / HTTPS_PROXY | HTTP proxy for all outbound requests |
NO_PROXY | Comma-separated hosts to bypass the proxy |
BASH_DEFAULT_TIMEOUT_MS | Default Bash tool timeout in milliseconds |
BASH_MAX_TIMEOUT_MS | Maximum allowed Bash tool timeout |
NO_COLOR | Disable ANSI color output |
DISABLE_AUTOUPDATER | Set to 1 to disable automatic updates |
export ANTHROPIC_API_KEY="sk-ant-..."
export ANTHROPIC_MODEL="claude-sonnet-4-6"
claude -p "What model are you using?"
Output:
I'm using claude-sonnet-4-6.
# Route through a corporate proxy
export HTTPS_PROXY="http://proxy.myhost:3128"
claude -p "Fetch the homepage title of example.com"
Output:
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.
# Load MCP config for a session
claude --mcp-config ./mcp-servers.json
Output: (none — opens REPL with MCP tools available)
{
"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.
| Key | Action |
|---|---|
Enter | Submit the current message |
Shift+Enter | Insert a newline without submitting |
Ctrl+C | Cancel the current in-progress operation |
Ctrl+D | Exit the session (equivalent to /exit) |
Ctrl+L | Clear the terminal screen |
Ctrl+R | Reverse-search prompt history |
↑ / ↓ | Navigate prompt history |
Tab | Autocomplete slash commands and file paths |
Escape | Cancel autocomplete / dismiss suggestion |
# 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).
| File | Scope | Description |
|---|---|---|
.claude/settings.local.json | Project (gitignored) | Personal overrides |
.claude/settings.json | Project | Project-level settings, hooks, permissions |
~/.claude/settings.json | User | Global user-level settings |
~/.claude/CLAUDE.md | User | Global memory injected into every session |
.claude/CLAUDE.md or <project>/CLAUDE.md | Project | Project-level memory (checked into git) |
.claude/commands/*.md | Project | Custom slash commands |
~/.claude/commands/*.md | User | Personal slash commands |
.claude/skills/<name>/SKILL.md | Project | Project-scoped custom skills |
~/.claude/skills/<name>/SKILL.md | User | Personal custom skills |
# Print the active settings (merged view)
claude --print "show me the model you are using and the active settings"
Output:
I'm using claude-sonnet-4-6. The active settings merge your project
.claude/settings.json with your user ~/.claude/settings.json.
# Open settings file in editor via slash command (in REPL)
# /config
Output: (none — opens settings.json in $EDITOR)
Output format reference
| Format | Flag value | Description |
|---|---|---|
| Text | text | Default — plain text streamed to stdout |
| JSON | json | Single JSON object printed after completion |
| Stream JSON | stream-json | Newline-delimited JSON events as they arrive |
# Capture JSON result in a shell variable
result=$(claude -p "Sum 2 + 2" --output-format json)
echo "$result" | jq -r '.result'
Output:
4
JSON result schema
The json output format returns a single object with these fields:
| Field | Type | Description |
|---|---|---|
type | string | Always "result" |
subtype | string | "success" or "error" |
result | string | The assistant's final text response |
session_id | string | Session ID for this run |
is_error | boolean | true if any tool call errored |
cost_usd | number | Estimated cost in USD |
duration_ms | number | Total wall-clock duration |
num_turns | number | Agent turns used |
claude -p "What is 2+2?" --output-format json | jq
Output:
{
"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:
| Type | Description |
|---|---|
system.init | Session start; carries session_id, model, tools |
assistant.message | Assistant message (may contain text or tool_use blocks) |
user.message | Tool result message from the harness |
result | Final result, same shape as json output |
error | Error mid-stream |
Exit codes
| Exit code | Meaning |
|---|---|
0 | Success |
1 | Generic error (auth, network, unknown flag) |
2 | Tool execution failed mid-task |
3 | Agent hit --max-turns without finishing |
4 | User cancelled (Ctrl+C) |
5 | Hook blocked the operation |
claude -p "test" --max-turns 1
echo "exit=$?"
Output:
(response truncated by max-turns)
exit=3
Common pitfalls
- Missing API key — if
ANTHROPIC_API_KEYis not set and not insettings.json,claudeexits with an auth error; set the key in your shell profile. --max-turnsin interactive mode —--max-turnsonly applies to-pnon-interactive mode; in the REPL it has no effect.--dangerously-skip-permissionsin shared environments — never use this flag on a shared machine; it disables all permission prompts and allows unrestricted tool execution.- Model ID typos — Claude Code validates model IDs on startup; an unknown ID causes an immediate error. Use
claude --versionand check the current model list if unsure. --system-promptreplaces, not appends — if you want to extend the default system prompt, use--append-system-promptinstead;--system-promptreplaces the entire system prompt.- 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. --add-dirrepeats, not concatenates — to add multiple directories pass--add-dirmultiple times, not a comma-separated string.stream-jsonwithout a parser — pipingstream-jsonto a script that expects whole JSON breaks; usejq -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.
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:
[
{"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.
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:
=== src/auth.ts ===
=== src/db.ts ===
Switch model mid-session with /model
> /model claude-opus-4-7
Output:
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.
{
"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.
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:
0.0034
Multi-directory workspace
Open Claude with access to multiple project roots — useful when refactoring shared code across sibling repos.
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
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)