Skip to main content
Tools & Guides
🇺🇸 · 28 min read

Claude Code CLI: Complete Command Reference and How-To Guide (2026)

Everything you need to know about the Claude Code CLI — from installation to advanced slash commands, CLAUDE.md configuration, MCP integration, and exam-day tips for the CCA-F certification.

Claude Code CLI: Complete Command Reference and How-To Guide (2026)

Claude Code is the command-line interface Anthropic built on top of the Claude API — and if you have not used it yet, you have been missing one of the most productive tools available to developers in 2026. Unlike browser-based chat, Claude Code runs directly in your terminal with full access to your files, your shell, and your project structure. It reads your codebase, reasons about it, writes and edits files, runs commands, and works through tasks from start to finish — with you directing it. As of early 2026, Claude Code authors 4% of all global GitHub commits. Anthropic's own engineering team ships 10–30 pull requests per day per engineer, every one generated by Claude. This guide covers every flag, every slash command, every configuration file, and every integration you need to use Claude Code like an expert — plus focused exam tips for CCA-F Domain 3.

1. What Is Claude Code

Claude Code is Anthropic's official CLI for the Claude AI platform. It is not a plugin, a wrapper around a web UI, or an autocomplete extension. It is an agentic coding tool that operates in your terminal with access to your local filesystem, your shell environment, and the internet. You give it a natural-language instruction — "add rate limiting to the login endpoint and write a test for it" — and it reads your files, builds a plan, implements the change, runs your tests, corrects failures, and confirms the result, all in a continuous loop that you supervise.

The underlying model is Claude (currently defaulting to claude-opus-4-5 in the CLI, though you can override this). The tools it uses — file reads, file writes, shell execution, web search — are exposed to the model as callable functions. At every step, the model decides which tool to invoke next, executes it, observes the result, and reasons about what to do next. This is the agent loop, and it is what makes Claude Code fundamentally different from a chatbot.

Claude Code runs everywhere developers already work:

  • Terminal (macOS, Windows, Linux)
  • VS Code via the official Claude Code extension
  • Claude desktop application (Code tab)
  • Claude iOS and Android applications
  • GitHub integration for automated PR review
  • Slack integration

The underlying agent is identical across all surfaces. The interface differs, but the capability does not.

Key fact for CCA-F candidates: The freeCodeCamp Claude Code Handbook (March 2026) reports that Anthropic's internal team ships 10–30 PRs per day per engineer via Claude, and 100% of PRs are reviewed by Claude before human review. Engineering productivity increased 200% since Claude Code adoption. These statistics are frequently referenced in certification study materials.

2. Installation and First Run

Claude Code is distributed as an npm package. You need Node.js 18 or later. Install it globally with a single command:

# Install globally
npm install -g @anthropic-ai/claude-code

# Check version
claude --version

# Update to latest
npm update -g @anthropic-ai/claude-code

After installation, you authenticate via the Anthropic API. Claude Code supports two authentication methods: Claude.ai subscription (Pro, Max, or Team plan) or a direct Anthropic API key.

# Option A: Authenticate via Claude.ai subscription
claude /login

# Option B: Set API key as environment variable
export ANTHROPIC_API_KEY=sk-ant-...

# Then launch in any project directory
cd my-project
claude

On first launch inside a directory, Claude Code reads the directory structure and is ready for instructions. You can immediately send natural-language requests like "explain what this project does" or "find all places we call the payments API." No setup beyond authentication is required for basic use.

For subscription plans: Claude Pro ($20/month) is sufficient for learning and personal projects. Claude Max ($100 or $200/month) is appropriate for sustained professional use where daily limits would otherwise interrupt your workflow. Boris Cherny, Head of Claude Code at Anthropic, recommends using the most capable model available (currently Opus 4.5/4.6) rather than reducing capability to save tokens — a weaker model takes more correction passes and often costs more per task than a capable one.

3. Full CLI Flag Reference

Running claude --help in your terminal displays the complete flag reference. Here is the full output with each flag explained:

claude [options] [prompt]

Options:
  -p, --print                  Print response and exit (non-interactive)
  --output-format <format>     Output format: text, json, stream-json
  --model <model>              Model to use (default: claude-opus-4-5)
  --system <prompt>            System prompt to inject
  --max-tokens <n>             Maximum tokens in the response
  --add-dir <path>             Add a directory to the session context
  --allowedTools <tools>       Comma-separated list of allowed tools
  --disallowedTools <tools>    Comma-separated list of disallowed tools
  --mcp-config <path>          Path to MCP server configuration file
  --resume <sessionId>         Resume a previous session by ID
  --continue                   Continue the most recent session
  --dangerously-skip-permissions  Skip permission checks (use with caution)
  -v, --verbose                Verbose output (shows tool calls and results)
  --version                    Show version number
  -h, --help                   Show help

Flag-by-flag breakdown

Flag What It Does Typical Use Case
-p, --print Runs Claude Code in non-interactive (headless) mode. Sends the prompt, executes, prints output to stdout, then exits. CI/CD pipelines, shell scripts, automation
--output-format text (default): plain text. json: structured JSON object. stream-json: JSON objects streamed line-by-line as they are produced. Scripting, piping output to jq, structured logging
--model Overrides the default model for this session. Accepts model identifiers like claude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5. Cost control for batch tasks, testing different models
--system Injects a system prompt at the start of the session, before any CLAUDE.md files are loaded. Useful for overriding persona or applying one-time instructions. Specialized automation, role-specific instructions
--max-tokens Caps the number of tokens in Claude's response. Does not affect input context — only output length. Useful for scripting where you need short, structured output. JSON generation, classification tasks
--add-dir Adds an additional directory to the session's reachable file context. Claude Code normally operates within the current working directory; this flag extends that boundary. Monorepos, shared library directories, reference implementations
--allowedTools Restricts Claude to only the specified tools for this session. Tools not listed are unavailable. Overrides settings.json for this run. Read-only audit sessions, security-constrained environments
--disallowedTools Blocks the specified tools for this session. Useful for disabling shell execution or web search when you only want file operations. Safe review sessions, restricted CI contexts
--mcp-config Specifies a path to a custom MCP configuration file, overriding the default .mcp.json location. Useful for project-specific or environment-specific MCP setups. Staging vs production MCP configs, CI environments
--resume <id> Resumes a specific previous session by its session ID. Claude Code sessions are persisted locally and can be continued after the terminal closes. Multi-day projects, interrupted sessions
--continue Shortcut that resumes the most recent session without needing to know its ID. Equivalent to --resume with the latest session ID. Picking up exactly where you left off
--dangerously-skip-permissions Disables all permission prompts. Claude executes every action without asking for confirmation. This is not plan mode — it is the opposite. Use only in trusted, isolated environments. Fully automated CI scripts with no human in the loop
-v, --verbose Exposes the internal tool calls — which files Claude reads, which commands it runs, what each tool returns. Useful for debugging unexpected behavior. Debugging, understanding Claude's reasoning process
CCA-F Exam Trap: Candidates frequently confuse --dangerously-skip-permissions with plan mode. They are opposites. Plan mode makes Claude reason WITHOUT executing. --dangerously-skip-permissions makes Claude execute WITHOUT asking. On the exam, a question asking "how do you make Claude propose changes before executing them" is answered with Plan Mode, not with any flag.

4. All Interactive Slash Commands

Once inside an interactive Claude Code session, you have access to a full set of slash commands. Type /help at any time to see the current list. Here is the complete reference as of 2026:

Command Description
/help Displays all available slash commands and keyboard shortcuts for the current session. Always the right first command in a new environment.
/clear Clears the entire conversation history from the current session. The files on disk remain unchanged — only the in-memory context resets. Use this when a session has drifted or accumulated too much stale context.
/compact Compresses the conversation history into a summary, freeing context window space while preserving the important information. Less aggressive than /clear — useful when you want to continue the session without losing all context.
/config Opens an interactive configuration menu where you can view and modify session-level settings: model selection, permission mode, and output preferences.
/cost Displays the current session's token usage and estimated API cost. Shows input tokens, output tokens, cache reads, and running total. Essential for monitoring usage in API-key billing mode.
/doctor Runs diagnostic checks on your Claude Code installation: Node.js version compatibility, API key validity, MCP server connectivity, and configuration file health. Use this when something is not behaving as expected.
/exit or /quit Exits the Claude Code session. The session is saved and can be resumed later with claude --continue or claude --resume <id>. Keyboard shortcut: Ctrl+D.
/init Initializes a CLAUDE.md file in the current project directory. Claude Code analyzes your project structure, stack, and key files, then generates a starter CLAUDE.md with appropriate context, conventions, and instructions. An excellent starting point for any new project.
/login Authenticates or re-authenticates with Anthropic. Opens the OAuth flow in your default browser if using Claude.ai subscription auth, or prompts for an API key if using direct API billing.
/logout Logs out from the current authentication. Removes the stored session token. Useful when switching accounts or shared machines.
/memory Opens the memory file editor. Claude Code maintains persistent memory files in ~/.claude/memory/ that carry context across sessions. This command lets you view, edit, or delete those memory entries.
/model Switches the active model mid-session. You can switch from Opus to Sonnet for cost-sensitive tasks and back to Opus for complex reasoning without ending the session.
/permissions Shows the current tool permissions for this session — which tools require confirmation before use, which are auto-allowed, and which are blocked. You can modify these interactively.
/pr_comments Fetches and displays comments from a GitHub pull request. Requires the GitHub MCP server to be connected. Used in the code review workflow to surface inline reviewer feedback directly in the terminal.
/release-notes Displays the release notes for the current version of Claude Code. Check this after an npm update to see what changed.
/review Activates code review mode. Claude Code reads the current diff or the specified files and produces a structured review: summary of changes, potential issues, suggestions for improvement, and security observations.
/status Shows the current session's status: active model, context window usage percentage, connected MCP servers, token counts, and session ID.
/terminal-setup Configures terminal-specific settings: color scheme, key bindings, prompt style, and whether to show diffs inline or in a split view. Useful when the default rendering does not match your terminal emulator.
Pro tip: The most important slash commands for day-to-day work are /status (monitor context fill level), /compact (rescue a session that is getting full), /model (switch to a cheaper model for repetitive tasks), and /cost (track API spend). Make these muscle memory within your first week.

5. CLAUDE.md — Project Configuration Files

CLAUDE.md is the most important configuration mechanism in Claude Code. It is a plain Markdown file that Claude Code reads automatically at the start of every session, before it reads anything else in your project. Think of it as a persistent system prompt that applies to every conversation in a given project or scope.

What CLAUDE.md Does

When Claude Code starts a session, it searches for and loads all applicable CLAUDE.md files. The content of these files is injected into the model's context as persistent instructions. Everything you put in CLAUDE.md is something Claude knows from the first message, without you having to repeat it. This is where you encode:

  • Your technology stack and why specific choices were made
  • Directory structure and what each major directory contains
  • Coding conventions: naming patterns, async style, error handling
  • Library choices: what is used and what is explicitly prohibited
  • Layer rules: "all database access goes through db/repos/ — no SQL in route files"
  • Security requirements specific to this project
  • Definition of done for a completed feature

The Three-Level Hierarchy

CLAUDE.md files exist at three levels, all of which are loaded simultaneously:

Level Location Scope Version Controlled?
User-level ~/.claude/CLAUDE.md This user only, across all projects No — personal preferences
Project-level ./CLAUDE.md or ./.claude/CLAUDE.md at project root All contributors to this project Yes — committed to git
Directory-level ./subdir/CLAUDE.md Active only when working in that subdirectory Yes — committed to git

Critical rule: these files are concatenated, not overridden. When Claude Code starts a session, it loads all applicable CLAUDE.md files and combines their contents. A project-level CLAUDE.md does not replace the user-level one. A subdirectory CLAUDE.md does not replace the project-level one. All levels apply simultaneously. This is one of the most common exam traps — more on that in the CCA-F section.

The @import Syntax

For large projects with many conventions, a single monolithic CLAUDE.md becomes unwieldy. Claude Code supports an @import directive that lets you split configuration into focused files:

# CLAUDE.md — top-level project config
# Core project context here...

@import ./standards/api-conventions.md
@import ./standards/testing-requirements.md
@import ./standards/security-rules.md

Each imported file is loaded and concatenated into the session context exactly as if it appeared inline. This lets you organize conventions by concern (API patterns, testing, security, database access) rather than dumping everything into one file.

Path-Scoped Rules in .claude/rules/

Claude Code also supports a .claude/rules/ directory where you can place Markdown files with YAML frontmatter that limits when those rules apply. This is more precise than @import for large codebases:

---
# .claude/rules/terraform-conventions.md
paths:
  - "terraform/**/*"
  - "infrastructure/**/*.tf"
---

## Terraform Conventions
- All resources must have a `Name` tag with the project prefix.
- Use `data` sources instead of hardcoded IDs.
- State must be stored in the designated S3 bucket.

This rule file only loads when Claude is editing files matching those glob patterns, reducing irrelevant context and token usage.

What a Good CLAUDE.md Looks Like

# Project: CertLand — Claude Context

## Architecture
- Backend: Django 5.1 + Django REST Framework
- Database: PostgreSQL (via psycopg3)
- Auth: JWT tokens via djangorestframework-simplejwt
- Frontend: React 18 + TypeScript (separate repo)

## Directory Structure
- apps/exams/ — exam management, questions, answers
- apps/users/ — user accounts, profiles, subscriptions
- apps/billing/ — Stripe integration, plan management
- apps/blog/ — blog posts, categories, tags

## Layer Rules
- All database access goes through the service layer in services.py
- No raw SQL in views; use Django ORM only
- No business logic in serializers; serializers format only

## Conventions
- All views are class-based (APIView subclasses)
- All external API calls are isolated in integrations/
- Use async/await for all database calls in service layer
- Errors: raise specific exception classes, never generic Exception

## Testing
- Framework: pytest + pytest-django
- Coverage requirement: 90% minimum before merge
- Every view needs both happy-path and error-path tests

## Definition of Done
A feature is complete when:
1. All specified behavior works across described scenarios
2. Edge cases in the spec are handled
3. Unit tests pass with 90%+ coverage
4. No linting errors (ruff + mypy)
5. PR description summarizes changes and test coverage

With this file in place, every session begins with full awareness of the project's architecture, conventions, and quality standards. You never have to re-explain the stack.

6. settings.json and .claude.json

Claude Code uses two categories of configuration files beyond CLAUDE.md. Understanding the difference is essential for CCA-F Domain 3.

settings.json — Permissions and Tool Control

The settings.json file controls Claude Code's behavior at the permission and tooling level — what it is allowed to do, which model to use, and which capabilities are enabled. There are two locations:

Location Scope Version Controlled?
~/.claude/settings.json Global — applies to this user on all projects No — personal
.claude/settings.json (project root) Project — applies to everyone on this project Yes — commit to git

Key fields in settings.json:

{
  "model": "claude-opus-4-5",
  "permissions": {
    "allow": [
      "Bash(git *)",
      "Bash(npm test)",
      "Bash(pytest *)",
      "Read(*)",
      "Edit(*)",
      "Write(*)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push --force *)",
      "Bash(curl * | bash)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/pre-bash.sh"
          }
        ]
      }
    ]
  }
}

The allow and deny arrays use pattern-matching strings. Bash(git *) allows any git command. Bash(rm -rf *) blocks any recursive force remove. When a tool call matches a deny rule, Claude Code blocks it before execution — the hook fires, but the command does not run.

.claude.json — Session Metadata

The .claude.json file (note: no settings in the name) stores session metadata and local state: the current session ID, recently accessed files, and feature flags that have been toggled in the UI. This file is maintained automatically by Claude Code and is typically gitignored. You should not edit it manually.

.mcp.json — MCP Server Configuration

The .mcp.json file declares which Model Context Protocol servers should load when Claude Code starts in this project directory. It lives at the project root and is committed to version control so every developer on the team gets the same MCP integrations:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/shared-templates"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}
CCA-F Exam Trap: The exam distinguishes between settings.json (permissions, model, hooks — behavioral configuration) and .mcp.json (which MCP servers to load — integration configuration). They serve different purposes and live in different files. A question about "configuring which MCP servers are available" points to .mcp.json. A question about "blocking a shell command from executing" points to settings.json permissions deny rules.

7. Plan Mode and Operational Modes

Claude Code has three distinct operational modes that govern how much it does before asking for your approval. Understanding these modes is one of the highest-leverage things you can learn for both day-to-day use and for the CCA-F exam.

Plan Mode

In Plan Mode, Claude Code reasons through the task and produces a structured plan — which files will be affected, what the implementation sequence will be, how data will flow — without writing a single line of code or executing any commands. You review the plan, modify it, reject portions of it, or approve it. Only when you release it does Claude begin implementation.

Boris Cherny, Head of Claude Code at Anthropic, uses Plan Mode for approximately 80% of his sessions. The mechanism is simple: a single instruction injected into the model's context — "please do not write any code yet" — changes Claude's behavior from execution to structured reasoning.

How to activate Plan Mode:

# In the terminal: press Shift+Tab twice to toggle Plan Mode

# In VS Code or desktop app: click the Plan Mode button in the interface

# Via a prompt instruction (works in any mode):
"Before writing any code, produce a structured plan showing which files
you will modify, in what order, and what change you will make to each.
Do not execute until I approve the plan."

What a good Plan Mode output looks like:

## Implementation Plan: Add rate limiting to /api/login

**Files to be modified:**
1. `apps/authentication/views.py` — add @ratelimit decorator to LoginView
2. `apps/authentication/urls.py` — no change needed
3. `requirements.txt` — add django-ratelimit==4.1.0

**Files to be created:**
4. `apps/authentication/tests/test_ratelimit.py` — integration tests

**Implementation sequence:**
1. Install django-ratelimit (pip install)
2. Add ratelimit config to settings.py (10 attempts / 5 minutes per IP)
3. Apply @ratelimit decorator to LoginView.post()
4. Write tests: happy path, rate limit hit (429 response), reset after window

**Edge cases to handle:**
- Load balancer forwarding headers (X-Forwarded-For)
- Admin users exempt from rate limiting
- Rate limit headers in response (X-RateLimit-Remaining)

Shall I proceed with this plan?

Ask Before Edits Mode (Default)

This is the default mode. Before modifying any existing file or creating new ones, Claude presents the proposed change as a diff (additions in green, deletions in red) and waits for your explicit approval. You can approve or reject each change individually. This mode is appropriate when you are working in an unfamiliar codebase, building something for the first time with Claude Code, or when the consequences of an incorrect edit are significant.

Automatic Edit Mode

In this mode, Claude writes files without asking for approval between each change. This is appropriate only after you have used Plan Mode and approved the plan. Once the strategy is confirmed, there is no additional value in approving each individual file write. Use --dangerously-skip-permissions in CI pipelines where there is no human in the loop at all.

Mode Summary for Exam Day: Plan Mode = Claude reasons, no execution. Ask Before Edits = Claude executes with per-change approval (default). Automatic Edit = Claude executes without per-change approval (use only after plan review). --dangerously-skip-permissions = Claude executes without any permission checks (CI/automation only, no human in the loop).

8. MCP Integration

The Model Context Protocol (MCP) is Anthropic's open protocol for connecting Claude Code to external tools and services. When an MCP server is connected, Claude Code gains the ability to act on that service directly — creating GitHub PRs, reading Notion pages, sending Slack messages, running Playwright browser sessions — without you switching contexts.

How to Add an MCP Server

There are two ways to add an MCP server: via the CLI command (recommended for getting started) or by editing .mcp.json directly.

Method 1: Via Claude Code session command

# Add a filesystem MCP server (user scope = applies to all projects)
# Inside a Claude Code session, type:
Add the following MCP server at user scope:
npx -y @modelcontextprotocol/server-filesystem /path/to/allowed/dir

# Claude Code writes the config to ~/.claude/mcp_settings.json automatically

Method 2: Edit .mcp.json directly

# .mcp.json in project root
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/project/src"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
        "SLACK_TEAM_ID": "${SLACK_TEAM_ID}"
      }
    }
  }
}

After adding an MCP server, restart the session (/exit and relaunch, or type /restart). Verify connected servers with:

/mcp

This lists all active MCP servers and their available tools. If a server appears in this list, it is connected and Claude can use its tools without any further setup.

Scope: User vs Project

Scope Location Applies To
User scope ~/.claude/mcp_settings.json All projects for this user
Project scope .mcp.json at project root This project only, all contributors

Most Useful MCP Servers

Server Package What It Enables
GitHub @modelcontextprotocol/server-github Create PRs, review open PRs, check CI status, create issues — all from the terminal
Filesystem @modelcontextprotocol/server-filesystem Extend Claude's file access beyond the current working directory
Playwright @modelcontextprotocol/server-playwright Real browser sessions: scraping, end-to-end test execution, web automation
Slack @modelcontextprotocol/server-slack Send and read Slack messages, monitor channels
Notion @notionhq/notion-mcp-server Read and write Notion pages and databases, update task status
PostgreSQL @modelcontextprotocol/server-postgres Query and inspect database schema directly in session

Anthropic maintains the official MCP server registry at github.com/modelcontextprotocol/servers. Each server has an installation command and configuration format. For third-party services (Notion, Airtable, Google Workspace), the service's own documentation provides the MCP configuration.

MCP Security Considerations

MCP servers extend Claude Code's reach into real external services. Two rules to follow:

  1. Grant only the access required. When configuring a filesystem server, specify the exact directories it can access rather than granting root-level access. When configuring Notion or GitHub, use tokens scoped to the specific resources Claude needs.
  2. Be specific in your instructions. Vague instructions are more likely to produce unexpected actions through MCP. "Update the project tracker" is ambiguous. "Add a row to the Sprint Tracker sheet with today's date and the values X, Y, Z" is not.

9. Hooks: PreToolUse and PostToolUse

Hooks are shell scripts that execute at specific points in Claude Code's tool execution lifecycle. They let you intercept, log, validate, or block Claude's actions — without modifying any Claude Code source code. Hooks are configured in settings.json under the hooks key.

Hook Types

Hook Type When It Fires Can Block Execution?
PreToolUse Before any tool call executes Yes — non-zero exit code blocks the tool call
PostToolUse After any tool call completes No — tool already executed

Hook Configuration in settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/pre-bash-check.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/post-edit-lint.sh"
          }
        ]
      }
    ]
  }
}

Practical Hook Examples

Use case 1: Log all shell commands before execution

#!/bin/bash
# .claude/hooks/pre-bash-check.sh
# Receives the command via stdin as JSON: {"command": "rm -rf /tmp/test"}

COMMAND=$(cat | python3 -c "import sys,json; print(json.load(sys.stdin)['command'])")
echo "[$(date)] Claude wants to run: $COMMAND" >> .claude/command-log.txt

# Block any rm -rf targeting non-tmp directories
if echo "$COMMAND" | grep -qE 'rm -rf [^/]|rm -rf /(?!tmp)'; then
  echo "BLOCKED: Dangerous rm -rf command" >&2
  exit 1
fi

exit 0  # Allow the command

Use case 2: Auto-run linter after every file edit

#!/bin/bash
# .claude/hooks/post-edit-lint.sh
# Runs after any Edit or Write tool call

FILE=$(cat | python3 -c "import sys,json; print(json.load(sys.stdin).get('file_path',''))")

if [[ "$FILE" == *.py ]]; then
  ruff check "$FILE" --fix --silent
  mypy "$FILE" --ignore-missing-imports --quiet
fi

if [[ "$FILE" == *.ts || "$FILE" == *.tsx ]]; then
  npx eslint "$FILE" --fix --quiet
fi

exit 0  # PostToolUse hooks can't block, but exit code is logged

Use case 3: Send a Slack notification when Claude makes production changes

#!/bin/bash
# .claude/hooks/post-deploy-notify.sh
COMMAND=$(cat | python3 -c "import sys,json; print(json.load(sys.stdin).get('command',''))")

if echo "$COMMAND" | grep -q "deploy\|kubectl apply\|terraform apply"; then
  curl -s -X POST "$SLACK_WEBHOOK_URL" \
    -H 'Content-type: application/json' \
    --data "{\"text\":\"Claude executed: $COMMAND at $(date)\"}"
fi
CCA-F key point: PreToolUse hooks are the correct answer for "how do you block a specific shell command from executing." PostToolUse hooks cannot block — the tool has already run. A non-zero exit code from a PreToolUse hook stops execution. The exam will test this distinction.

10. Non-Interactive Scripting with -p

The -p (or --print) flag turns Claude Code into a non-interactive command-line tool. There is no terminal UI, no follow-up questions, no waiting for input. Claude processes the prompt, executes, prints output to stdout, and exits. This is the foundation of every CI/CD integration, shell script, and automated pipeline that uses Claude Code.

Basic Non-Interactive Usage

# Basic: print response and exit
claude -p "Summarize the changes in the last git commit in 3 bullet points"

# With structured JSON output
claude -p "Review the file src/auth.py for security issues" --output-format json

# Pipe a file into the prompt
claude -p "$(cat CHANGELOG.md) — summarize the breaking changes in v2.0"

# Combine with other Unix tools
git diff HEAD~1 | claude -p "Review this diff for potential bugs" --output-format text

CI/CD Pipeline Integration

The most common Claude Code CI/CD integration is automated PR review. Here is a complete GitHub Actions workflow:

# .github/workflows/claude-code-review.yml
name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Generate diff
        run: |
          git diff origin/${{ github.base_ref }}...HEAD > /tmp/pr-diff.txt

      - name: Run Claude Code review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          REVIEW=$(claude -p "$(cat /tmp/pr-diff.txt)" \
            --system "You are a senior engineer reviewing a pull request. \
              Focus on: security vulnerabilities, logic errors, missing error handling, \
              and test coverage gaps. Format output as Markdown." \
            --output-format text \
            --max-tokens 2000)
          echo "$REVIEW" > /tmp/review-output.md

      - name: Post review as PR comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('/tmp/review-output.md', 'utf8');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.payload.pull_request.number,
              body: `## Claude Code Review\n\n${review}`
            });

Structured JSON Output for Scripting

When you need to parse Claude's output programmatically, use --output-format json:

# Extract specific fields with jq
claude -p "List the top 3 security issues in src/ as JSON array" \
  --output-format json | jq '.result'

# Use stream-json for real-time processing of long outputs
claude -p "Analyze all Python files in src/ for type annotation coverage" \
  --output-format stream-json | while read -r line; do
    echo "$line" | jq -r '.content // empty'
  done

Combining -p with --allowedTools for Safety

# Read-only audit: Claude can only read files, no writes or shell commands
claude -p "Audit this codebase for hardcoded secrets and credentials" \
  --allowedTools "Read,Glob,Grep" \
  --output-format json
CCA-F key point: The -p flag is the answer to any exam question about "headless mode," "CI/CD integration," or "non-interactive execution." It is also how you combine Claude Code with --output-format json to produce machine-readable output for automated pipelines. Remember: -p means "no interactive session, print and exit."

11. CCA-F Domain 3 Exam Tips

Domain 3 of the CCA-F exam — Claude Code Configuration & Workflows — accounts for 20% of the exam score. It is the domain with the highest density of trap questions, because most of the traps exploit subtle misunderstandings about configuration hierarchy, flag behavior, and the difference between similarly-named mechanisms. Here are the most important patterns to internalize before exam day.

Trap 1: CLAUDE.md Files Are Concatenated, Not Overridden

The most common wrong answer on the CCA-F exam is "the project CLAUDE.md overrides the global CLAUDE.md." This sounds intuitive (like CSS specificity or environment variable shadowing), but it is factually wrong. All three levels — user, project, directory — are concatenated into a single combined context. Every instruction from every applicable CLAUDE.md file is active simultaneously.

Memory trick: Think of CLAUDE.md files as layers of paint that all show through (additive), not as layers that cover the one below (overriding). Every instruction from every level is visible and active.

Trap 2: CLAUDE.md vs Skills (Agent Skills)

The exam distinguishes between CLAUDE.md (passive context — instructions Claude reads and applies to everything it does) and Agent Skills (active automation — reusable slash commands that trigger specific workflows). They serve different purposes:

Mechanism Purpose How It Works
CLAUDE.md Project context, conventions, standards Loaded automatically at session start; applies passively to all actions
Agent Skills Reusable, triggerable workflows (e.g., /deploy, /review-pr) Defined as markdown files in .claude/skills/; invoked explicitly by slash command

If the question asks "where do you define a reusable workflow that teammates can trigger with /deploy," the answer is Agent Skills, not CLAUDE.md. If it asks "where do you define conventions that always apply without being invoked," the answer is CLAUDE.md.

Trap 3: .claude.json vs settings.json — Know the Difference

settings.json is the configuration file you write and commit. It contains permissions, model selection, and hooks. It is intentional and maintained by developers.

.claude.json is the state file maintained automatically by Claude Code. It stores session metadata, recently accessed files, and UI state. You do not edit it. You do not commit it. It is typically gitignored. If the exam asks "which file stores permission rules," the answer is settings.json. If it asks "which file tracks session state," the answer is .claude.json.

Trap 4: Plan Mode Keyboard Shortcut

The keyboard shortcut to toggle Plan Mode in terminal is Shift+Tab twice. In VS Code and the desktop app, there is a Plan Mode button in the interface. The exam has tested both the shortcut and the mechanism (Claude reasons without executing) in Domain 3 questions.

Trap 5: PreToolUse Can Block, PostToolUse Cannot

Any question about "preventing a tool from executing" or "blocking a dangerous command" points to PreToolUse hooks with a non-zero exit code. PostToolUse hooks fire after execution — they can log, notify, or trigger follow-up actions, but they cannot undo or block what already happened.

Quick Reference: Domain 3 Exam Cheat Sheet

Scenario Correct Answer
Make Claude propose changes before executing Plan Mode (Shift+Tab twice, or Plan Mode button)
Run Claude Code in a CI/CD pipeline with no human interaction claude -p "prompt" --output-format json
Apply conventions to all sessions for all teammates on a project Project-level CLAUDE.md (committed to git)
Apply personal preferences across all your projects User-level CLAUDE.md at ~/.claude/CLAUDE.md
Apply subdirectory-specific conventions (e.g., Terraform files only) Directory-level CLAUDE.md or path-scoped rules in .claude/rules/
Prevent a specific shell command from ever executing PreToolUse hook with non-zero exit code, or deny rule in settings.json
Auto-run linter after every file edit PostToolUse hook on Edit/Write matcher
Connect Claude to GitHub, Slack, or Notion MCP server configured in .mcp.json or via session command
Create a reusable /deploy workflow teammates can invoke Agent Skill in .claude/skills/deploy.md
What happens when project CLAUDE.md conflicts with user CLAUDE.md? Both apply simultaneously (concatenated, not overridden)
Which file stores session state and is typically gitignored? .claude.json (not settings.json)
How to extend Claude's file access beyond the working directory --add-dir <path> flag, or Filesystem MCP server

Practice CCA-F Domain 3 Questions on CertLand

CertLand's CCA-F practice exam includes 606 questions across all five domains, with detailed explanations for every answer. Domain 3 questions cover CLAUDE.md hierarchy, plan mode, hooks, -p flag behavior, settings.json permissions, and MCP configuration — exactly the traps covered in this guide.

Start Practicing Free →

Claude Code is one of the most capable developer tools available in 2026, and mastering its configuration system is the difference between using it casually and deploying it as a serious productivity multiplier. Whether you are preparing for the CCA-F or simply trying to get more out of your daily development workflow, the patterns in this guide — CLAUDE.md hierarchy, plan mode discipline, MCP integration, and hook-based automation — are where the professional-level usage lives.

🏆 Lifetime Deal Pay once, use forever

Get lifetime access — one payment

Full access to 82,997+ questions, AI Coach, and every premium guide. No subscription, no renewals. Yours forever.

Lifetime access

one-time payment

vs subscription

$7.49/mo billed yearly

Lifetime saves you 10× over 5 years

82,997+ practice questions AI Coach + study plans All premium guides Future exams included No subscription ever

Comments

Sign in to leave a comment.

No comments yet. Be the first!

Comments are reviewed before publication.