Claude Code CLI Cheatsheet - Anthropic AI Coding Agent Full Reference

Claude Code targets developers who want the model to read, edit, and run commands inside a repo from the terminal, plus automation engineers wiring it into CI. As Anthropic official agentic coding tool it differs from chat-style assistants, and drives pipelines headlessly via -p + --output-format json or iterative multi-turn REPL sessions. This sheet surfaces the key commands for install/auth, session resume, permission modes, and MCP extensibility so you can start on real projects immediately.

AI CLI·53 commands·Last updated 2026-08-05
claude-codeclaudeanthropicaicliagentCoding Agent

Typical Use Case

For developers pairing in the terminal and for teams putting Claude into a pipeline. The key split is between the interactive REPL and print mode with -p, which is what scripts and CI should use, and which needs --output-format json to be parseable at all. The sheet covers the recurring questions: how to stop runaway sessions with --max-turns and --max-budget-usd together, how to control permissions with plan mode for read-only work and --add-dir for extra directories, how to supply context by referencing @file and @dir rather than pasting, and the four ways to add an MCP server. Session slash commands and project-level commands are listed alongside.

Install & Auth 7

npm install -g @anthropic-ai/claude-code
Install Claude Code globally via npm
claude --version
Print the installed version
npm update -g @anthropic-ai/claude-code
Upgrade to the latest version
claude update
Update to the latest version from within the CLI
claude auth login
Interactive sign-in to your Anthropic account
claude auth status
Show current authentication status
claude auth logout
Sign out

Launch & Run 6

claude
Start an interactive REPL in the current directory
claude "Refactor the user-auth module to use the new session API"
Start a session with an initial prompt
cat error.log | claude -p "Explain this error and suggest a fix"
Pipe content in and process it in print mode
claude -c
Continue the most recent conversation (--continue)
claude -r "abc123" "Finish the PR"
Resume a specific conversation by session ID (--resume)
claude -c -p "Check for type errors"
Continue the recent conversation in print mode for automation

CLI Flags 13

claude -p -m claude-sonnet-4 "Write a Python function to parse CSV"
Set the model and run in print mode
claude -p --output-format json "List all TODO comments in this project"
Output JSON for scripting and parsing
claude -p --max-turns 5 "Refactor the auth module"
Cap agentic turns to prevent runaway operations
claude --max-budget-usd 2 "Implement the login page"
Cap API spend in -p mode
claude --add-dir ../frontend ../backend
Grant file access to extra working directories
claude --system-prompt "You are a security auditor"
Replace the entire system prompt
claude --append-system-prompt "Use TypeScript strict mode"
Append instructions to the default system prompt
claude --permission-mode plan
Start in plan mode (read-only, no file changes)
claude --dangerously-skip-permissions
Skip all permission prompts (trusted environments only, use with caution)
claude -w feat/login
Start in an isolated git worktree (--worktree)
claude --effort high "Design the cache layer architecture"
Set reasoning effort: low/medium/high/xhigh/max
claude --bg "Run the test suite"
Start as a background agent and return immediately
claude --verbose
Show full turn-by-turn tool output

Session Slash Commands 7

/clear
Clear conversation history for a fresh task
/compact
Summarize the conversation to free context window space
/context
Visualize context window usage and optimization tips
/resume
Reopen a past session by name or from a picker
/branch
Fork the conversation to try a different direction
/rewind
Roll code and conversation back to a checkpoint
/exit
Quit the REPL

Project & Dev Slash Commands 10

/init
Generate a starter CLAUDE.md for the project
/memory
Edit CLAUDE.md files and manage auto-memory
/mcp
Manage MCP server connections interactively
/agents
Configure subagent settings
/permissions
Set allow/ask/deny rules for tools
/hooks
View hook configurations
/plan
Enter plan mode before a large change
/model
Switch the active model
/diff
Open the interactive diff viewer
/code-review --fix
Review the current diff (optionally auto-fix)

MCP Server Management 7

claude mcp add --transport http <name> <url>
Add an HTTP MCP server (recommended transport)
claude mcp add <name> -- <args...>
Add a stdio MCP server; command follows --
claude mcp add-json '<json>'
Add a complex MCP server from JSON config
claude mcp list
List configured MCP servers
claude mcp get <name>
Show a server configuration
claude mcp remove <name>
Remove an MCP server
claude mcp add-from-claude-desktop
Import MCP servers from Claude Desktop

Prompt File References 3

Review @./src/components/Button.tsx
Reference a single file with @ in the prompt
Compare @src/old.js with @src/new.js
Reference multiple files to compare
Explain the structure of @./src
Reference a whole directory for context

Parameter matrix

ParameterEffectExample
-pPrint mode; no interactive session, for scripts and CIclaude -p "list all TODO comments in this project"
--output-format jsonOutput as JSON for easy programmatic parsingclaude -p --output-format json "list TODOs"
-m <model>Specify the modelclaude -p -m claude-sonnet-4 "write a function that parses CSV"
--max-turns <n>Cap the number of agent turns to prevent runaway operationsclaude -p --max-turns 5 "refactor the auth module"
--max-budget-usd <n>Cap API spend in print modeclaude --max-budget-usd 2 "implement the login page"
--add-dir <dir>Authorize additional working directories for accessclaude --add-dir ../frontend ../backend
--permission-mode planRead-only plan mode; does not modify filesclaude --permission-mode plan
--dangerously-skip-permissionsSkip all permission confirmations; only for trusted environmentsclaude --dangerously-skip-permissions
-c / -r <id>Continue the most recent session / resume a specific sessionclaude -r "abc123" "continue finishing the PR"
-w <branch>Start in a dedicated git worktreeclaude -w feat/login
--system-prompt <s>Replace the entire system promptclaude --system-prompt "you are a security auditor"
--append-system-prompt <s>Append instructions after the default system promptclaude --append-system-prompt "use TypeScript strict mode"
--effort <lvl>Set reasoning effort to low/medium/high/xhigh/maxclaude --effort high "design the caching layer architecture"
--bgStart as a background agent and return immediatelyclaude --bg "run the test suite"
--verboseShow per-turn tool execution detailsclaude --verbose
mcp add --transport httpAdd an HTTP-transport MCP server (recommended)claude mcp add --transport http docs https://example.com/mcp
mcp add <name> -- <args...>Add a stdio type MCP serverclaude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem .
mcp add-json <json>Add a complex MCP server from a JSON configclaude mcp add-json '{"name":"x"}'
@./pathReference files or directories as context in the promptReview @./src/components/Button.tsx

Common pitfalls

SymptomA CI script cannot read the result; the process seems to print content and then exit.

CauseWithout -p the command enters the interactive REPL, and in a non-TTY environment there is no stable output channel.

FixAlways use claude -p, and add --output-format json when you need structured results.

SymptomAn automated task wrecks the repository, or loops endlessly editing the same file.

CauseNeither agent turns nor spend is capped, so it keeps trying when it hits a hard spot.

FixUse --max-turns 5 and --max-budget-usd 2 as a double safeguard; before a big change, first use --permission-mode plan to get a plan only.

SymptomThe model says it cannot see files in adjacent or parent directories.

CauseBy default only the current working directory is authorized, and cross-directory access is blocked.

FixUse --add-dir ../frontend ../backend to explicitly authorize the directories that need access.

SymptomLate in a long session it starts ignoring early constraints and responds more slowly.

CauseThe context window is filled with conversation history, and tool output consumes a large share of it.

FixUse /context to inspect usage and /compact to summarize and compress; if the task truly shifts topic, just /clear.

SymptomPrompts keep getting longer, and the model still answers wrong even after you paste in file contents.

CauseHand-copied content loses context and is hard to maintain; pasting large blocks instead dilutes the weight of your instructions.

FixSwitch to file references like @./src so the tool reads on demand; it is accurate and easy to version in the repository.

SymptomThe command changed files but left no rollback point, so damage is hard to undo.

CauseThere are no checkpoints and no version-control safety net.

FixUse /rewind to roll back to a checkpoint, or start in a dedicated worktree (-w feat/login) to keep the main branch clean.

SymptomAn MCP server is configured but its tools do not work.

CauseFor stdio type the command was placed before --, or for HTTP type --transport http is missing, causing a config type mismatch.

FixVerify with claude mcp list and claude mcp get <name>, and if needed use claude mcp add-json to paste the full JSON config directly.

Troubleshooting

  1. 1Confirm installation and authentication status

    claude --version && claude auth status

    Both the version and login must be fine before you can enter a session; if not logged in, run claude auth login to fix it.

  2. 2Verify the non-interactive call chain with JSON output

    claude -p --output-format json "list all TODO comments in this project"

    Getting parseable JSON means -p mode and the model call both work, ready to wire into scripts.

  3. 3Pipe in context and take only the printed result

    cat error.log | claude -p "explain this error and give a fix"

    This validates both piped input and print mode; the error log enters the session as context.

  4. 4Probe the scope of a change with a low-cost, budget-capped call

    claude --max-budget-usd 2 "implement the login page"

    It aborts automatically when over budget and shows the amount spent, good for estimating cost locally first.

  5. 5Check MCP server registration

    claude mcp list

    Lists configured servers; if a name is missing, the add command did not take effect.

  6. 6Try changes in a dedicated worktree

    claude -w feat/login "implement the login page"

    Changes are isolated in a separate worktree so the main branch is untouched; merge after verification.

Command Examples

Fix a failing test in print mode

claude -p --output-format json "run the tests, locate the root cause from the failure output and propose a fix" cat log.txt | claude -p "analyze the root cause of this error and give the fix steps"

-p outputs the result and exits; adding --output-format json makes it directly parseable by scripts and is the de facto standard for automated calls.

Output

{"status":"root cause identified","cause":"the user-auth module does not handle an empty token","fix":"add a null check before session validation"}

Resume last session to continue a refactor

claude -c echo "error log" | claude -c -p "check for type errors"

Use -c (most recent session) or -r <session-id> (a specific session) to resume painlessly after restarting the terminal.

Output

(enters the REPL, restoring the earlier context and changes already made, so you can keep chatting or edit files)

Plan before a large change

claude --permission-mode plan "refactor the payments module; first give the change list and risk points"

In plan mode the model only reads and analyzes; once you confirm the plan, run it under default permissions, which significantly reduces rework.

Output

(outputs only a plan report, modifying no files)

Add a Postgres MCP server

claude mcp add --transport http my-pg http://localhost:8080/mcp claude mcp list

Once connected, you can have Claude query the database directly in a session and write code from the results, saving the manual copy-paste of query output.

Output

✔ Added MCP server "my-pg" (HTTP)

Common Pitfalls

  • --dangerously-skip-permissions skips all prompts so the model can edit files and run commands directly — only in trusted/throwaway environments.
  • --max-budget-usd only caps -p print mode; an interactive REPL needs another budget mechanism, so do not rely on it to stop long sessions.
  • Changes are diffed before applying, but editing CLAUDE.md/AGENTS.md or dependencies changes future behavior — review those memory files before big changes.
  • stdio MCP servers are spawned by the claude subprocess; if one dies it can slow the agent, so check /mcp on stalls.

Tips

  • For scripts and CI prefer claude -p --output-format json: print mode + JSON is the de-facto standard for automation.
  • Cap long tasks or bounded budgets with both --max-turns and --max-budget-usd to avoid runaway API spend.
  • Give Claude context with @file / @dir references — more accurate and maintainable than pasting file contents into the prompt.
  • Before big changes, enter read-only /plan mode to confirm the approach, then grant permissions to execute — far less rework.

FAQ

What is the difference between Claude Code -p (print mode) and the interactive REPL?

The interactive REPL suits exploratory development with multi-turn conversations and file edits; -p print mode suits scripts and pipelines — it runs once, prints the result, and exits, and supports --output-format json for programmatic parsing.

How do I let Claude Code auto-approve all actions without confirmation prompts?

Use --dangerously-skip-permissions to skip all prompts, or set --permission-mode to acceptEdits / bypassPermissions. Only use these in trusted environments, since they let the agent modify files and run commands directly.

How does Claude Code connect to MCP servers to extend its capabilities?

Manage connections interactively via the /mcp slash command, or add external MCP servers with claude mcp add <name> <command> (e.g. database, filesystem, API). Once connected, the agent can call those tools during a session.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Aug 5, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us