Claude Code Slash Commands, Shortcuts & CLI Reference

Complete reference for every Claude Code slash command, keyboard shortcut, CLI flag, and environment variable. Plus custom commands with Skills.

Bruce

Claude CodeCommandsCLI ReferenceProductivity

AI Guides

3272 Words

2026-03-05 06:00 +0000


Complete reference guide for Claude Code slash commands, keyboard shortcuts, and CLI flags

Claude Code has over 40 built-in slash commands, dozens of keyboard shortcuts, and a rich set of CLI flags. Most developers use about five of them. The rest sit undiscovered, which means missed opportunities to save time, reduce token costs, and automate repetitive workflows.

This is the reference you bookmark. Every slash command with what it does and when to use it. Every keyboard shortcut worth memorizing. Every CLI flag for scripting and automation. Plus how to build your own custom commands using Skills.

No fluff. Just the complete command reference for Claude Code in 2026.

Built-in Slash Commands

Type / at the start of your input to see all available commands. Type any letters after / to filter the list. Here is every built-in command, organized by what you use them for.

Session Management

These commands control your conversation lifecycle – starting fresh, resuming old work, and managing context.

CommandWhat It Does
/clearWipe conversation history and start fresh. Aliases: /reset, /new
/compact [instructions]Compress conversation to save context. Optionally specify what to keep: /compact retain the API design decisions
/resume [session]Resume a previous session by ID or name, or open a session picker. Alias: /continue
/fork [name]Branch the current conversation into a new session from this point
/rename [name]Rename the current session. Without a name, auto-generates one from history
/rewindRestore code and conversation to a previous point. Alias: /checkpoint
/exitExit Claude Code. Alias: /quit

When to use what:

  • /compact when context usage exceeds 80% but you are still working on the same task. Add focus instructions to control what survives: /compact keep the database schema and error handling patterns
  • /clear when switching to a completely different task. Old context would confuse Claude
  • /resume when you closed a session yesterday and want to pick up where you left off
# Check context usage first
/context

# If context is getting full, compact with focus
/compact retain the authentication flow and test results

# If switching tasks entirely, clear everything
/clear

Information and Diagnostics

Commands that show you what is happening – costs, status, context usage, and environment health.

CommandWhat It Does
/costShow token usage and cost for the current session
/usageShow plan usage limits and rate limit status
/contextVisualize context window usage as a colored grid
/statusShow version, model, account, and connectivity info
/doctorRun diagnostics on your Claude Code installation
/helpList all available commands
/statsVisualize daily usage, session history, and streaks
/diffOpen interactive diff viewer showing uncommitted changes and per-turn diffs
/export [filename]Export conversation as plain text to a file or clipboard
/copyCopy last assistant response to clipboard. Shows picker for code blocks
/release-notesView the full changelog
/insightsGenerate a report analyzing your Claude Code sessions

Power user tip: Run /cost periodically during long sessions. A single agentic loop can burn through tokens faster than you expect. If costs are climbing, use /compact to reduce context size or switch to a cheaper model with /model sonnet.

# Quick session health check
/cost          # How much have I spent?
/context       # How full is my context window?
/usage         # Am I near my rate limit?

Model and Mode Control

Switch models, toggle modes, and change how Claude behaves.

CommandWhat It Does
/model [model]Switch model. Use left/right arrows to adjust effort level
/fast [on|off]Toggle fast mode (same model, faster output)
/planEnter plan mode – Claude proposes actions before executing
/vimToggle between Vim and normal editing modes
/output-style [style]Switch output style: Default, Explanatory, or Learning
/themeChange color theme (light, dark, colorblind-accessible options)

Model switching strategy: Start with Sonnet for most tasks – it handles 80% of work at lower cost. Switch to Opus for complex architecture decisions, subtle bugs, or tasks requiring deep reasoning. Switch back when the hard part is done.

# Start a session with Sonnet (default, cheaper)
/model sonnet

# Hit a tricky bug? Switch to Opus
/model opus

# Done with the hard part, switch back
/model sonnet

Configuration and Permissions

Manage settings, permissions, authentication, and project setup.

CommandWhat It Does
/configOpen settings interface. Alias: /settings
/permissionsView or update tool permissions. Alias: /allowed-tools
/initInitialize project with a CLAUDE.md file
/memoryEdit CLAUDE.md memory files, toggle auto-memory
/loginSign in to your Anthropic account
/logoutSign out from your Anthropic account
/hooksConfigure and manage lifecycle hooks
/agentsManage subagent configurations
/skillsList available skills
/mcpManage MCP server connections
/pluginManage Claude Code plugins
/terminal-setupConfigure terminal keybindings (Shift+Enter, etc.)
/keybindingsOpen or create keybindings configuration
/sandboxToggle sandbox mode for isolated execution
/extra-usageConfigure extra usage when rate limits hit
/privacy-settingsView and update privacy settings (Pro/Max only)
/statuslineConfigure terminal status line display

Code Review and PR Workflow

Commands for working with pull requests and code review.

CommandWhat It Does
/reviewReview a pull request for quality, correctness, and security. Pass a PR number or omit to list open PRs
/pr-comments [PR]Fetch and display comments from a GitHub PR. Auto-detects current branch PR
/security-reviewAnalyze pending changes for security vulnerabilities
/install-github-appSet up Claude GitHub Actions for automated PR review

These commands require the gh CLI to be installed and authenticated. If you have not set it up:

# Install GitHub CLI
brew install gh

# Authenticate
gh auth login

# Now you can use PR commands in Claude Code
/review 42        # Review PR #42
/pr-comments      # Show comments on current branch's PR
/security-review  # Security audit of uncommitted changes

Working Directories and Integration

CommandWhat It Does
/add-dir <path>Add a new working directory to the session
/ideManage IDE integrations and show status
/chromeConfigure Chrome browser integration
/remote-controlMake session available for remote control from claude.ai. Alias: /rc
/desktopContinue session in Claude Code Desktop app (macOS/Windows). Alias: /app
/tasksList and manage background tasks
/feedback [report]Submit feedback about Claude Code. Alias: /bug

Keyboard Shortcuts

Memorizing even a few of these shortcuts will noticeably speed up your workflow. Think of them like IDE shortcuts – the investment pays off every session.

Essential Shortcuts (Learn These First)

ShortcutWhat It DoesWhen to Use
EscapeCancel current generationClaude is going down the wrong path
Escape + EscapeRewind or summarizeUndo Claude’s last actions
Ctrl+CExit sessionDone working (press twice)
Ctrl+RReverse search historyFind a previous prompt you typed
Ctrl+TToggle task listTrack progress on multi-step work
Shift+TabCycle permission modesSwitch between Auto-Accept, Plan, and normal mode
?Show available shortcutsForgot a shortcut
ShortcutWhat It Does
Up/Down arrowsNavigate command history
Ctrl+KDelete to end of line
Ctrl+UDelete entire line
Ctrl+YPaste deleted text
Alt+BMove cursor back one word
Alt+FMove cursor forward one word
Ctrl+LClear terminal screen (keeps history)

Mode and Display Toggles

ShortcutWhat It Does
Ctrl+OToggle verbose output (see detailed tool usage)
Ctrl+BBackground running tasks (tmux users: press twice)
Ctrl+GOpen current prompt in external text editor
Option+P / Alt+PSwitch model without clearing prompt
Option+T / Alt+TToggle extended thinking

Multiline Input

Writing multi-line prompts requires special key combinations since Enter submits the message.

MethodShortcutNotes
Backslash escape\ + EnterWorks in all terminals
macOS defaultOption+EnterDefault on macOS
Shift+EnterShift+EnterWorks in iTerm2, WezTerm, Ghostty, Kitty out of the box
Line feedCtrl+JWorks everywhere
Paste modePaste directlyFor code blocks and logs

If Shift+Enter does not work in your terminal, run /terminal-setup to install the keybinding.

Quick Input Prefixes

PrefixWhat It DoesExample
/Slash command or skill/compact retain error patterns
!Direct bash command! git status
@File path autocomplete@src/main.ts

The ! prefix is powerful – it runs a shell command directly and adds the output to conversation context without Claude interpreting or approving it. Use it for quick checks while maintaining context:

! npm test                # Run tests, output goes into context
! git log --oneline -5    # Check recent commits
! cat .env.example        # Show file contents

CLI Flags Reference

CLI flags let you customize Claude Code’s behavior from the command line. They are essential for scripting, CI/CD pipelines, and automation.

Session Control

FlagDescriptionExample
--continue, -cResume most recent conversationclaude -c
--resume, -rResume session by ID or nameclaude -r auth-refactor
--from-prResume sessions linked to a PRclaude --from-pr 123
--fork-sessionFork into new session when resumingclaude -r abc123 --fork-session
--session-idUse specific session UUIDclaude --session-id "550e8400-..."
--worktree, -wStart in isolated git worktreeclaude -w feature-auth

Model and Behavior

FlagDescriptionExample
--modelSet model (sonnet, opus, or full name)claude --model opus
--fallback-modelAuto-fallback when overloaded (print mode)claude -p --fallback-model sonnet "query"
--permission-modeStart in a specific permission modeclaude --permission-mode plan
--agentSpecify an agent for the sessionclaude --agent my-custom-agent
--agentsDefine custom subagents via JSONSee example below

Print mode (-p) is the key to scripting with Claude Code. It sends a query and exits – no interactive session.

FlagDescriptionExample
--print, -pNon-interactive modeclaude -p "explain this codebase"
--output-formatOutput as text, json, or stream-jsonclaude -p --output-format json "query"
--json-schemaValidate output against JSON Schemaclaude -p --json-schema '{...}' "query"
--max-turnsLimit agentic turnsclaude -p --max-turns 3 "query"
--max-budget-usdCap spending for this runclaude -p --max-budget-usd 5.00 "query"
--input-formatInput format: text or stream-jsonclaude -p --input-format stream-json

Practical scripting examples:

# Generate API docs and save to file
claude -p "Generate API documentation for src/api/" --output-format text > api-docs.md

# Get structured analysis as JSON
claude -p "Analyze the error handling in this project" --output-format json | jq '.result'

# Limit spending on expensive operations
claude -p --max-budget-usd 2.00 --max-turns 5 "Refactor the auth module"

# Pipe content for analysis
cat error.log | claude -p "What caused this crash?"

# CI/CD: Check code quality with budget cap
claude -p --max-budget-usd 1.00 --output-format json \
  "Review the last commit for security issues" | jq '.result'

Permission and Tool Control

FlagDescriptionExample
--allowedToolsTools that run without permission prompts--allowedTools "Bash(git log:*)" "Read"
--disallowedToolsTools completely blocked--disallowedTools "Bash(rm *)" "Edit"
--toolsRestrict which built-in tools are available--tools "Bash,Edit,Read"
--dangerously-skip-permissionsSkip all permission prompts (use with extreme caution)Not recommended for production

The --allowedTools flag is the safer alternative to skipping permissions entirely. You get automation without giving Claude carte blanche:

# Allow only read operations and git commands
claude -p --allowedTools "Bash(git log:*)" "Bash(git diff:*)" "Read" "Grep" "Glob" \
  "Generate a code review for the last 3 commits"

System Prompt Customization

FlagDescriptionUse Case
--system-promptReplace entire system promptComplete control over behavior
--system-prompt-fileReplace with file contentsVersion-controlled prompts
--append-system-promptAdd to default promptExtra rules while keeping defaults
--append-system-prompt-fileAppend file contentsLoad rules from files

For most use cases, --append-system-prompt is the safest option – it keeps Claude Code’s built-in capabilities while adding your custom rules:

# Add project-specific rules
claude --append-system-prompt "Always use TypeScript. Never use any. Include JSDoc comments."

# Load rules from a file for team consistency
claude --append-system-prompt-file ./team-rules.txt

MCP and Extensions

FlagDescriptionExample
--mcp-configLoad MCP servers from JSON fileclaude --mcp-config ./mcp.json
--strict-mcp-configOnly use servers from --mcp-configclaude --strict-mcp-config --mcp-config ./mcp.json
--chromeEnable Chrome browser integrationclaude --chrome
--plugin-dirLoad plugins from directoryclaude --plugin-dir ./my-plugins
--add-dirAdd extra working directoriesclaude --add-dir ../apps ../lib

Other Useful Flags

FlagDescription
--verboseVerbose logging with full turn-by-turn output
--debugEnable debug mode, optionally filter by category: --debug "api,mcp"
--version, -vShow version number
--ideAuto-connect to IDE on startup
--initRun initialization hooks on startup
--remoteCreate a web session on claude.ai
--teleportResume a web session in your local terminal
--disable-slash-commandsDisable all skills and commands for this session
--settingsLoad additional settings from a JSON file

Custom Commands with Skills

Built-in commands cover general needs. But your team has specific workflows – deployment checklists, code review processes, documentation formats. This is where custom commands come in.

Claude Code supports two approaches: legacy slash commands (files in .claude/commands/) and the newer Skills system (files in .claude/skills/). Skills are the recommended approach – they do everything commands do, plus auto-triggering and supporting files.

Creating a Custom Skill

A Skill is a folder containing a SKILL.md file with YAML frontmatter and Markdown instructions.

Step 1: Create the skill directory.

# Project-level skill (shared with team via Git)
mkdir -p .claude/skills/deploy

# Personal skill (available in all your projects)
mkdir -p ~/.claude/skills/deploy

Step 2: Write the SKILL.md file.

---
name: deploy
description: Deploy the application to staging or production. Use when the user mentions deploying, releasing, or shipping.
---

# Deployment Workflow

## Pre-deployment Checks
1. Run the full test suite: `npm test`
2. Check for uncommitted changes: `git status`
3. Verify you're on the correct branch

## Deploy Steps
1. Build the production bundle: `npm run build`
2. Run database migrations if needed
3. Deploy using: `./scripts/deploy.sh <environment>`
4. Verify the deployment health check

## Post-deployment
1. Monitor error rates for 15 minutes
2. Run smoke tests against the deployed environment
3. Update the deployment log

Step 3: Use it.

# Manual invocation
/deploy

# Or just describe what you want -- Claude auto-detects the skill
"Deploy the latest changes to staging"

Skill Frontmatter Options

The YAML frontmatter controls how and when your skill activates:

---
name: code-review
description: Thorough code review following team standards
# Optional fields:
user_invocable: true       # Allow manual /code-review invocation (default: true)
auto_invocable: true       # Allow Claude to auto-trigger (default: true)
model: opus                # Force a specific model for this skill
tools:                     # Restrict which tools this skill can use
  - Read
  - Grep
  - Glob
---

Skills vs Legacy Commands

FeatureLegacy CommandsSkills
Location.claude/commands/name.md.claude/skills/name/SKILL.md
InvocationManual (/name) onlyAuto-triggered + manual
Supporting filesNoYes (templates, scripts, examples in same folder)
FrontmatterOptionalFull control (model, tools, invocation)
StatusStill worksRecommended

Legacy commands keep working. If you have existing .claude/commands/ files, they will continue to function. Migrate when convenient – or do not. A Skill and a command with the same name will resolve to the Skill.

For a deep dive on building advanced Skills, see our Claude Code Skills Guide.

Environment Variables

Environment variables configure Claude Code at a deeper level than settings or flags. Set them in your shell profile (~/.zshrc, ~/.bashrc) or per-session.

Authentication

VariablePurpose
ANTHROPIC_API_KEYYour Anthropic API key. Leave unset to use subscription-based auth
ANTHROPIC_AUTH_TOKENCustom Authorization header value (prefixed with Bearer )

Cloud Provider Configuration

VariablePurpose
CLAUDE_CODE_USE_BEDROCKSet to 1 to route through AWS Bedrock
CLAUDE_CODE_USE_VERTEXSet to 1 to route through Google Vertex AI
CLAUDE_CODE_USE_FOUNDRYSet to 1 to route through Microsoft Foundry

Model Configuration

VariablePurpose
ANTHROPIC_MODELOverride the default model
ANTHROPIC_DEFAULT_SONNET_MODELDefault Sonnet-class model ID
ANTHROPIC_DEFAULT_OPUS_MODELDefault Opus-class model ID
ANTHROPIC_DEFAULT_HAIKU_MODELDefault Haiku-class model ID
CLAUDE_CODE_EFFORT_LEVELThinking effort: low, medium, or high
CLAUDE_CODE_MAX_OUTPUT_TOKENSMax output tokens (default 32,000; max 64,000)
CLAUDE_CODE_SUBAGENT_MODELModel for subagents

Bash Execution

VariablePurposeDefault
BASH_DEFAULT_TIMEOUT_MSDefault timeout for bash commandsVaries
BASH_MAX_TIMEOUT_MSMaximum timeout the model can setVaries
BASH_MAX_OUTPUT_LENGTHMax characters before truncationVaries
CLAUDE_CODE_SHELLOverride automatic shell detectionAuto
CLAUDE_CODE_SHELL_PREFIXPrefix to wrap all bash commandsNone

Feature Toggles

VariableSet to 1 to…
CLAUDE_CODE_DISABLE_AUTO_MEMORYDisable auto-memory
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background task functionality
CLAUDE_CODE_DISABLE_FAST_MODEDisable fast mode
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONSRemove git workflow instructions from system prompt
DISABLE_AUTOUPDATERDisable automatic updates
DISABLE_PROMPT_CACHINGDisable prompt caching
DISABLE_COST_WARNINGSSuppress cost warning messages

Setting environment variables:

# In ~/.zshrc or ~/.bashrc
export ANTHROPIC_API_KEY="sk-ant-..."
export CLAUDE_CODE_EFFORT_LEVEL="high"
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000

# Per-session override
CLAUDE_CODE_EFFORT_LEVEL=low claude -p "Quick summary of this file"

# For AWS Bedrock users
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1

Power User Tips

1. Chain Commands for Context Efficiency

Instead of sending multiple messages, front-load context before your request:

# Bad: multiple turns, wastes tokens
"What does the auth module do?"
"Now add rate limiting to it"
"Now write tests for the rate limiting"

# Good: single prompt with full context
"Add rate limiting to the auth module in src/auth/ and write tests.
 Rate limit: 100 requests per minute per IP.
 Use the existing Redis connection for storage.
 Follow the test patterns in tests/auth/"

2. Monitor Costs with /cost

Get into the habit of checking /cost every 15-20 minutes during active sessions. Token usage can spike during agentic loops where Claude reads files, edits, runs tests, and iterates.

If costs are climbing faster than expected:

  • Run /compact to reduce context size
  • Switch to /model sonnet for less complex subtasks
  • Break large tasks into smaller, focused sessions

3. Use /compact Strategically

/compact is not just a panic button when context is full. Use it proactively:

# After finishing a subtask, compact before starting the next
/compact retain the API schema and test results, discard the debugging steps

# Before a complex operation, make room
/compact keep only the project architecture and current task requirements

4. Script Repetitive Workflows

Combine -p mode with shell scripting for tasks you run regularly:

#!/bin/bash
# daily-review.sh -- Morning code review routine

echo "=== Reviewing yesterday's changes ==="
claude -p --max-budget-usd 1.00 --output-format text \
  "Review all commits from the last 24 hours. Flag any security issues,
   missing tests, or code quality problems. Be concise." \
  --allowedTools "Bash(git log:*)" "Bash(git diff:*)" "Bash(git show:*)" "Read" "Grep"

echo "=== Done ==="

5. Background Long-Running Commands

When Claude is running a slow command (tests, builds, deployments), press Ctrl+B to send it to the background. You can keep working on your prompt while the command finishes:

# Claude starts running "npm test" (takes 2 minutes)
# Press Ctrl+B to background it
# Continue typing your next instruction
# Claude retrieves the output when it's done

6. Use Vim Mode for Complex Prompts

If you write long, detailed prompts, enable Vim mode with /vim. You get full Vim navigation (hjkl, word motions, text objects) and editing (dd, ciw, yy) right in the Claude Code input. Toggle it off anytime with /vim again.

7. Define Subagents for Specialized Tasks

Use the --agents flag to create focused subagents that Claude can delegate to:

claude --agents '{
  "test-writer": {
    "description": "Writes comprehensive tests. Use after any code change.",
    "prompt": "You write thorough tests. Cover happy path, edge cases, and error conditions.",
    "tools": ["Read", "Edit", "Bash"],
    "model": "sonnet"
  },
  "security-reviewer": {
    "description": "Reviews code for security vulnerabilities.",
    "prompt": "You are a security expert. Find injection, auth, and data exposure risks.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "opus"
  }
}'

Quick Reference Card

Here is the cheat sheet. Print it, pin it, or keep it in a second terminal.

Daily essentials:

ActionCommand
Check costs/cost
Check context usage/context
Compress context/compact [focus]
Start fresh/clear
Switch model/model sonnet or /model opus
Resume last sessionclaude -c
Run diagnostics/doctor

Keyboard shortcuts:

ActionShortcut
Cancel generationEscape
Undo Claude’s actionsEscape + Escape
Search historyCtrl+R
Toggle task listCtrl+T
Verbose outputCtrl+O
Cycle permission modesShift+Tab
Background commandCtrl+B
Switch modelAlt+P

Scripting pattern:

claude -p "your query" \
  --output-format json \
  --max-turns 5 \
  --max-budget-usd 2.00 \
  --allowedTools "Read" "Grep" "Glob"

Comments

Join the discussion — requires a GitHub account