Andrew Mercer
on this page

Claude Code CLI — Comprehensive Guide

A practical reference for installing, configuring, and working with Claude Code from the terminal.


1. What Claude Code Is

Claude Code is Anthropic's agentic coding tool for the terminal. You describe a task in plain language, and Claude reads your files, runs commands (via a sandboxed Bash tool), edits code, runs tests, and iterates — all inside an "agentic loop" where it decides which tools to call and keeps working until the task is done or it needs your input.

It's also available as a VS Code / JetBrains extension, a desktop app, on the web (claude.ai/code), in Slack, and in CI/CD (GitHub Actions, GitLab CI). This guide covers the terminal CLI specifically.


2. Installation

System requirements

  • macOS 13.0+, Windows 10 1809+/Server 2019+, Ubuntu 20.04+, Debian 10+, or Alpine Linux 3.19+
  • 4 GB+ RAM, x64 or ARM64
  • Bash, Zsh, PowerShell, or CMD
# macOS, Linux, WSL
curl -fsSL https://claude.ai/install.sh | bash
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex

Native installs auto-update in the background. Alternatives:

brew install --cask claude-code          # Homebrew (manual updates: brew upgrade claude-code)
winget install Anthropic.ClaudeCode      # WinGet
npm install -g @anthropic-ai/claude-code # npm (needs Node.js 22+, don't use sudo)

Debian/Ubuntu (apt), Fedora/RHEL (dnf), and Alpine (apk) also have signed repos — see the setup docs if you want OS-managed packages instead of the self-updating binary.

Verify and diagnose

claude --version   # confirms the binary works
claude doctor       # read-only diagnostics: install health, settings validation, etc.

Authenticate

claude              # first run prompts a browser login

Requires a Pro, Max, Team, Enterprise, or Console account (the free claude.ai plan doesn't include Claude Code). If ANTHROPIC_API_KEY is set in your environment, Claude Code uses that instead of prompting for a browser login. You can also route through Amazon Bedrock, Google Vertex AI (Agent Platform), or Microsoft Foundry for enterprise billing — relevant given your Azure background, though note Claude Code's cloud-provider integration story is Bedrock/Vertex/Foundry, not Azure OpenAI directly.

Other auth commands:

claude auth login --console   # sign in via Console (API billing) instead of a subscription
claude auth status            # check login state (exit 0 = logged in)
claude auth logout
claude setup-token             # generate a long-lived OAuth token for CI/scripts

3. First Session

cd /path/to/your/project
claude

This opens an interactive REPL scoped to that directory. You don't need to manually add context — Claude reads project files as needed. Try:

what does this project do?
add a hello world function to the main file
commit my changes with a descriptive message

Type /help inside a session for available commands, / to browse commands and skills, Tab for completion, ↑ for history, and Shift+Tab to cycle permission modes.


4. Core Concepts

The agentic loop — Claude reasons, picks a tool (Read, Edit, Write, Bash, Glob, Grep, WebFetch, WebSearch, etc.), observes the result, and repeats until done. You can interrupt and steer at any point — it's a conversation, not a one-shot script.

Sessions — Each conversation is a session tied to a working directory. Sessions can be resumed, branched, or run across git worktrees for parallel work.

Context window — Long sessions get compacted automatically as they approach the limit; you can check usage with /context and manage it proactively (see §9).

Permission modes — Govern what Claude can do without asking you first (see §7).


5. Essential CLI Commands

Command What it does
claude Start an interactive session
claude "task" Start interactive session with an initial prompt
claude -p "query" Print mode — run once, print result, exit (no REPL)
cat file \| claude -p "query" Pipe file content in for one-off processing
claude -c Continue the most recent conversation in this directory
claude -r "<name-or-id>" "query" Resume a specific session
claude --resume / claude -r Show an interactive session picker
claude update Update to the latest version
claude doctor Installation/config diagnostics
claude mcp Configure MCP servers
claude agents Open agent view — monitor/dispatch parallel background sessions
claude attach <id> Attach to a running background session
claude project purge [path] Delete local state (transcripts, history) for a project
claude plugin Manage plugins

Session slash-commands (typed inside a running session): /help, /clear, /exit, /resume, /memory, /config, /permissions, /hooks, /mcp, /diff, /statusline, /rename, /usage, /context, /compact.


6. Key CLI Flags

Claude Code has a lot of flags — claude --help doesn't list all of them. The ones you'll actually reach for:

Model & effort

claude --model claude-sonnet-5       # or an alias: sonnet, opus, haiku, fable
claude --effort high                 # low | medium | high | xhigh | max | ultracode
claude --fallback-model sonnet,haiku # auto-fallback chain if primary is overloaded

Permissions

claude --permission-mode plan                    # start in a given mode
claude --dangerously-skip-permissions             # skip all prompts (bypassPermissions)
claude --allowedTools "Bash(git log *)" "Read"    # pre-approve specific tool patterns
claude --disallowedTools "Edit"                   # remove/deny tools

Scripting / non-interactive

claude -p "query" --output-format json      # text | json | stream-json
claude -p "query" --max-turns 3
claude -p "query" --max-budget-usd 5.00
claude --bare -p "query"                    # skip hooks/skills/MCP discovery — fastest cold start

Working directory / isolation

claude --add-dir ../apps ../lib     # grant access to extra directories
claude -w feature-auth               # start in an isolated git worktree
claude --agents '{"reviewer":{"description":"...","prompt":"..."}}'  # define a subagent inline

System prompt

claude --append-system-prompt "Always use TypeScript"
claude --system-prompt-file ./prompts/review.txt   # full replacement

Other useful ones: --session-id <uuid>, --name/-n <label>, --settings <path-or-json>, --chrome (browser automation), --json-schema '<schema>' (structured output), --verbose.

Full reference: code.claude.com/docs/en/cli-reference.


7. Permissions & Modes

Claude Code asks before doing anything risky, unless you tell it otherwise. Modes, cycled with Shift+Tab mid-session or set with --permission-mode:

Mode Behavior
default / manual Prompts for anything not explicitly allowed
acceptEdits Auto-approves file edits, still prompts for other risky actions
plan Analyze-only — Claude proposes a plan before touching anything
auto A classifier auto-approves most actions; default starting mode for interactive sessions on Pro/Max/Team
dontAsk Only pre-approved tools run; everything else is silently denied
bypassPermissions Skips essentially all checks — use with care, especially in CI

Fine-grained rules live in settings (permissions.allow, .ask, .deny), support wildcards, and can be scoped per-tool (Bash command patterns, file paths, MCP tools, etc.). /permissions inside a session lets you inspect and edit these interactively.

For DevOps/CI use, --dangerously-skip-permissions or dontAsk with a tight allowlist are the common patterns — see §9 for headless mode specifics.


8. Configuration: CLAUDE.md, Settings, and the .claude Directory

CLAUDE.md — A markdown file Claude auto-loads at session start containing project-specific instructions: build commands, conventions, architecture notes, things to avoid. Place it at your project root (./CLAUDE.md) or user-level (~/.claude/CLAUDE.md) for global preferences. Claude Code also supports .claude/rules/ for path-scoped instructions in larger repos, and "auto memory" — Claude can write durable notes about your project as it works, viewable/editable via /memory.

settings.json — Layered configuration: - User: ~/.claude/settings.json - Project (shared, committed): .claude/settings.json - Project (local, gitignored): .claude/settings.local.json - Organization (managed, IT-controlled): takes precedence over everything

Precedence: managed settings > local project > shared project > user, with permission lists merging rather than overriding. Common keys: model, permissions, env, hooks, statusLine, autoUpdatesChannel, sandbox.*. Full key list: settings-reference doc — it's enormous (model config, sandboxing, MCP policy, git attribution, etc.).

The .claude directory holds config, plugin data, session transcripts, and application state. claude project purge cleans up per-project local state without touching your global settings.


9. Non-Interactive / Headless Mode (relevant for CI, scripts, cron)

Since you build a lot of CLI tooling and CI pipelines, this is probably the most useful section:

# One-shot, machine-readable output
claude -p "summarize failing tests" --output-format json

# Pipe data in
cat build.log | claude -p "explain this failure"

# Streaming output (for long-running scripted tasks)
claude -p "refactor module X" --output-format stream-json --verbose

# In a script/CI job, no prompts allowed:
claude -p "run the migration and report status" \
  --permission-prompts none \
  --allowedTools "Bash(alembic *)" "Read" \
  --max-turns 10
  • --permission-prompts none denies anything not pre-approved rather than hanging waiting for input — essential for unattended runs.
  • --bare skips hook/skill/plugin/MCP/CLAUDE.md discovery for faster, more deterministic cold starts in scripted contexts.
  • --max-budget-usd and --max-turns cap runaway cost/loops.
  • GitHub Actions and GitLab CI both have first-party integrations (github-actions, gitlab-ci-cd docs) if you want @claude mentions to trigger runs directly in your existing GitLab CI pipelines rather than shelling out yourself.
  • claude agents --json lists active background sessions for scripting against.

For anything more structured than shell scripting — e.g. embedding Claude in one of your Rust tools — the Agent SDK (@anthropic-ai/claude-agent-sdk / claude-agent-sdk for Python) wraps the same engine programmatically with typed messages, custom tools, and structured output support.


10. MCP (Model Context Protocol) — Connecting External Tools

MCP lets Claude Code call out to external services — databases, GitLab/GitHub, internal APIs, your homelab services, etc.

claude mcp add my-server -- npx -y some-mcp-server   # local stdio server
claude mcp add --transport http my-remote https://example.com/mcp
claude mcp list
claude mcp login <name>     # OAuth flow for a server that needs sign-in

Servers can be scoped local (just you, this project), project (.mcp.json, shared via git), or user (global). Given your homelab and self-hosted service pattern, a project-scoped .mcp.json pointing at internal tools (e.g. your job-tracker or company-tracker APIs) is a natural fit if you ever want Claude Code to query them directly during a session.


11. Hooks — Automating Around Claude's Actions

Hooks run your own shell commands at lifecycle points (before/after a tool call, on session start/stop, after file edits, etc.). Typical uses: auto-format after edits, block edits to protected paths, notify on completion, re-inject context after compaction. Configure via /hooks or directly in settings under the hooks key. Given you already build CLI automation, hooks are the idiomatic way to wire Claude Code into your existing tooling (e.g., triggering your http-manager link-checker after doc edits).


12. Skills, Subagents, and Plugins

  • Skills — reusable, discoverable instructions Claude loads on demand (like a runbook). Live in .claude/skills/ or come bundled/from plugins.
  • Subagents — specialized delegate agents (code reviewer, debugger, etc.) that run in isolated context, invoked automatically or explicitly. Define them in .claude/agents/ or inline with --agents.
  • Plugins — bundles of skills, agents, hooks, and MCP servers, installable from marketplaces (claude plugin install <name>@<marketplace>). Useful for standardizing conventions across a team.

13. Everyday Workflows

claude "explain this codebase"
claude "there's a bug where X happens — fix it"
claude "refactor the auth module to use async/await"
claude "write unit tests for the calculator functions"
claude "review my changes and suggest improvements"

Git worktrees for parallel work: claude -w feature-name isolates Claude's changes in a separate worktree, so you can run several unrelated tasks concurrently without them stepping on each other.

Plan first, then execute: --permission-mode plan (or Shift+Tab to Plan mode mid-session) makes Claude lay out an approach before touching files — good for anything non-trivial.

Resume across a break:

claude -c              # most recent conversation, this directory
claude --resume         # interactive picker across all sessions

14. Updating & Uninstalling

claude update                 # manual update

Native installs auto-update in the background by default; control this with autoUpdatesChannel (latest vs stable) or DISABLE_AUTOUPDATER=1 in settings env.

To fully remove (native install):

rm -f ~/.local/bin/claude
rm -rf ~/.local/share/claude
rm -rf ~/.claude ~/.claude.json     # also wipes settings, MCP config, session history

15. Quick Troubleshooting

  • claude doctor first, always — it covers install health and settings validation without starting a session.
  • Auth issues → claude auth status, then /login inside a session or claude auth login.
  • Broken/conflicting config → claude --safe-mode disables all customizations (CLAUDE.md, skills, plugins, hooks, MCP, themes) to isolate the cause.
  • Command-not-found or version mismatches → check for a conflicting install (Homebrew + native + npm all on PATH is a common culprit).

Further Reading

  • Full docs map (auto-generated index): code.claude.com/docs/en/claude_code_docs_map.md
  • CLI reference (every flag): code.claude.com/docs/en/cli-reference
  • Settings reference (every config key): code.claude.com/docs/en/settings-reference
  • Best practices: code.claude.com/docs/en/best-practices
  • Agent SDK (programmatic use): code.claude.com/docs/en/agent-sdk/overview