Skip to content

Command Line Mastery: Tips 26-35

You’re 40 messages deep, Claude has lost the thread, every response is slower than the last, and you can’t remember which of yesterday’s sessions had the schema work. The Claude Code CLI has a precise answer for each of those problems — resuming the right session, clearing context at the right moment, and shelling out to headless mode for the parts a script should own. These tips cover the commands and shortcuts that separate a fluent power user from someone fighting the REPL.

  • The correct claude -r / claude -c resume model (by session name or picker — no fabricated index numbers)
  • Headless one-liners that produce parseable JSON for commit messages, reviews, and CI
  • Copy-paste prompts for a conventional-commit generator, a pre-commit console.log scan, and a reusable PR-review command
  • A “When This Breaks” section for the failure modes that actually bite: wrong session resumed, runaway --dangerously-skip-permissions, and JSON parsing that silently fails

Understanding Claude Code’s command structure enables fluid interaction:

Terminal window
# Start interactive session
claude
# Run one-time task
claude "implement user authentication with JWT"
# Quick query with immediate exit
claude -p "explain this regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/"
# Continue most recent conversation in this directory
claude -c
# Resume a session: opens an interactive picker...
claude -r
# ...or resume directly by ID or name, with a query
claude -r "auth-refactor" "Finish this PR"

Quick Reference

  • -p, --print: Run single prompt and exit (non-interactive)
  • -c, --continue: Continue most recent conversation in this directory
  • -r, --resume: Resume a session by ID or name, or show an interactive picker
  • --model: Specify model to use
  • -v, --verbose: Show turn-by-turn output
  • --add-dir: Include additional directories

Slash commands provide quick access to Claude Code’s features:

Essential Slash Commands:
/help - Show all available commands and usage
/init - Initialize project with CLAUDE.md
/review - Request comprehensive code review
/clear - Clear conversation history (frees context; faster, cheaper turns follow)
/config - View or modify configuration
/status - View account and system status
/memory - Edit CLAUDE.md memory files
/permissions - Manage tool permissions
/cost - Check token usage and costs
/compact - Compress conversation history
/add-dir - Add directory to workspace
/hooks - Configure automation hooks
/terminal-setup - Configure terminal settings
/ide - Connect to IDE for diagnostics
/install-github-app - Enable GitHub integration

Custom command examples:

Terminal window
# Create a custom test command
echo 'Generate comprehensive tests for: $ARGUMENTS' > .claude/commands/test.md
# Use it inside the REPL
/test UserService.js
# Create a deployment command
echo 'Deploy to staging following our process: $ARGUMENTS' > .claude/commands/deploy-staging.md
# Use it
/deploy-staging --version 2.1.0

One of the most impactful habits for Claude Code efficiency:

Terminal window
# Clear at the start of each new task
/clear
# Why this matters:
# 1. Saves tokens (no history to process)
# 2. Prevents context confusion
# 3. Avoids compaction overhead
# 4. Faster response times
# 5. Cleaner mental model

When to Clear

  • Starting a new feature
  • Switching between different parts of codebase
  • After completing a task
  • When context becomes confused
  • Before complex architectural discussions

Best practices for context management:

Terminal window
# Good workflow
claude
/clear
# Work on authentication feature
# Complete authentication
/clear
# Work on payment integration
# Complete payment integration
# Bad workflow
claude
# Work on authentication
# Work on payment without clearing
# Work on UI without clearing
# Context becomes muddled

Claude Code persists sessions across runs, but resume works by ID, name, or picker — there is no numeric index like claude -r 5. Knowing the exact forms saves you from re-opening the wrong conversation:

Terminal window
# Within a session, navigate prior prompts with arrow keys
# Previous prompt
# Next prompt
# Open an interactive picker of recent sessions
claude -r
# Use arrow keys or type to filter, then Enter to resume
# Resume directly by session ID or name, and queue a query
claude -r "auth-refactor" "Finish this PR"
# Continue the most recent session in the current directory
claude -c

Name your sessions intentionally (the picker and -r "<name>" both rely on it) and the “which one had the schema work?” problem disappears.

Terminal window
# Show the picker, then choose with arrow keys / search
claude -r

Efficient file referencing is crucial for providing context:

  1. Using @ mentions

    Refactor @UserService.js to use dependency injection
    Update @components/Button.tsx to support dark mode
  2. Drag and drop with Shift

    • Normal drag: Opens file in new tab
    • Shift + drag: References file in Claude Code
  3. Glob patterns

    Review all test files: @**/*.test.js
    Update all React components: @components/**/*.tsx
  4. Multiple file references

    Ensure consistency between @User.model.js, @user.service.js, and @user.controller.js

Claude Code excels at understanding intent without specific syntax:

Instead of memorizing commands, just describe what you want:
"Fix the bug in user authentication"
"Add comprehensive tests for the payment module"
"Refactor this function to be more readable"
"Help me understand how the caching layer works"
"Create a new feature for exporting data to CSV"
"Review my code for security vulnerabilities"
"Optimize this query that's running slowly"
"Update the documentation for the API endpoints"

Natural Language Patterns

Claude Code understands:

  • Technical descriptions
  • Colloquial requests
  • Partial information
  • Context from previous messages
  • Implied requirements
  • Domain-specific terminology

Examples of natural language understanding:

Terminal window
# Vague request → Claude asks clarifying questions
"Make this faster"
> I see you want to improve performance. Could you specify:
> 1. Which part is slow?
> 2. What's the current performance?
> 3. What's your target?
# Context-aware request
"Do the same thing for the product service"
> I'll apply the same dependency injection pattern I used
> for UserService to the ProductService
# Implicit requirements
"Make this production ready"
> I'll add:
> - Error handling
> - Input validation
> - Logging
> - Tests
> - Documentation

Claude Code provides sophisticated git integration:

Terminal window
# Status and changes
"What files have I changed?"
"Show me the git diff"
"What's on the staging area?"
# Committing
"Commit my changes with a descriptive message"
"Create a commit following conventional commits"
"Amend the last commit"
# Branches
"Create a new branch called feature/user-auth"
"Switch to the main branch"
"Show me all branches"

Essential keyboard shortcuts for productivity:

Universal Shortcuts:
- Escape - Stop current operation (not exit)
- Escape Escape - Rewind code + conversation to an earlier checkpoint
- Tab - Command/file completion
- Shift+Enter - New line in prompt (after setup)
- Ctrl+C - Cancel/interrupt current operation
- Ctrl+D - Exit Claude Code (EOF)
- Ctrl+L - Clear screen
- Ctrl+R - Search command history
File Operations:
- Ctrl+V - Paste image (not Cmd+V on Mac)
- Shift+Drag - Reference file (not open)
Navigation:
- ↑/↓ - Navigate command history
- Page Up/Down - Scroll through output
- Home/End - Jump to start/end
Special:
- # - Quick CLAUDE.md update
- / - Start slash command
- @ - Start file reference

Platform Differences

  • macOS: Use Ctrl for special functions, not Cmd
  • Windows/Linux: Standard Ctrl shortcuts work
  • Terminal app: May need to configure key bindings

Tip 34: Use One-Shot Commands for Quick Tasks

Section titled “Tip 34: Use One-Shot Commands for Quick Tasks”

For automation and quick operations, always reach for -p (print/non-interactive). Bare claude "..." launches the REPL and will hang in a pipeline; claude -p "..." runs once and exits. Redirect a single file with <, and pipe a directory’s worth of code with cat/git diff — you cannot redirect stdin from a directory (< src/ errors with “Is a directory”).

Terminal window
# Quick formatting (single file via stdin)
claude -p "format this SQL query" < query.sql > formatted.sql
# Code review of a diff
git diff | claude -p "review these changes for security issues"
# Documentation generation
claude -p "generate JSDoc comments" < utils.js > documented.js
# Batch operations
for file in *.js; do
claude -p "add error handling" < "$file" > "safe_$file"
done
# Pipeline integration
git diff | claude -p "explain these changes" | tee explanation.md
# Review a whole directory by piping its files in (not `< src/`)
cat src/**/*.js | claude -p "review for performance issues"

Integration examples:

.git/hooks/pre-commit
# Git hooks
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.js$')
for file in $files; do
claude -p "list any console.log statements in this file" < "$file"
done
# CI/CD pipeline
# .github/workflows/review.yml
- name: Claude Review
run: |
git diff origin/main...HEAD | claude -p "review these changes for performance issues"

Extend Claude Code with project-specific commands:

  1. Create command directory

    Terminal window
    mkdir -p .claude/commands
  2. Create command file

    .claude/commands/feature.md
    Create a new feature with our standard structure:
    Feature name: $ARGUMENTS
    1. Create feature branch
    2. Set up folder structure:
    - /features/$ARGUMENTS/
    - /features/$ARGUMENTS/components/
    - /features/$ARGUMENTS/hooks/
    - /features/$ARGUMENTS/tests/
    3. Create index files with exports
    4. Add to main router
    5. Create basic test setup
  3. Use the command

    Terminal window
    /feature user-profile
  4. Create nested (namespaced) commands

    .claude/commands/db/migrate.md
    mkdir -p .claude/commands/db
    # A command in a subdirectory is colon-namespaced by that directory.
    # Now use: /db:migrate (the subdirectory name becomes the prefix)

Advanced command examples:

.claude/commands/review.md
Perform comprehensive code review:
- Security vulnerabilities
- Performance issues
- Code style violations
- Missing tests
- Documentation gaps
Focus on: $ARGUMENTS
# .claude/commands/refactor.md
Refactor following our patterns:
- Extract constants
- Add type safety
- Improve naming
- Reduce complexity
- Add error handling
Target: $ARGUMENTS
# .claude/commands/test/integration.md
Create integration tests for: $ARGUMENTS
- Use our test utilities
- Mock external services
- Test error scenarios
- Verify response format

Command Best Practices

  • Keep commands focused and specific
  • Use $ARGUMENTS for flexibility
  • Include context and requirements
  • Version control command files
  • Share useful commands with team

Combining these command-line techniques creates a powerful workflow:

Terminal window
# Start fresh
claude --dangerously-skip-permissions
/clear
# Set up workspace
/add-dir ../shared
/add-dir ../backend
# Quick task
"Create user authentication with JWT"
# Review and test
/review
"Add comprehensive tests"
# Natural git workflow
"Commit these changes"
"Create a PR"
# Went down the wrong path? Rewind to an earlier checkpoint
Escape Escape # restores code + conversation, then re-prompt from there
# Quick check
/cost # Monitor token usage
# Continue tomorrow
claude -c # Pick up where you left off

These three earn their keep at the command line — one headless one-shot, one pre-commit guard, and one reusable review command.

The CLI is fast, which means a wrong assumption burns time or tokens before you notice. The failure modes that actually bite:

  • Resume opens the wrong session. claude -r without an argument shows a picker; resuming “the last one” with -c grabs whatever ran most recently in this directory — which may not be the work you meant. Name sessions and resume by name (claude -r "auth-refactor") when it matters. There is no claude -r 5 index to fall back on.
  • --dangerously-skip-permissions on a runaway task. Skipping approvals is great until Claude loops on a failing build and burns tokens unattended. Use it for short, well-scoped tasks; keep /cost open, and never pair it with a vague prompt like “fix everything”.
  • Headless JSON parsing silently fails. claude -p "..." defaults to plain text, so piping it to jq errors or returns null. Add --output-format json and read the .result field (or .structured_output when you pass --json-schema). A hook that forgets this will pass when it should block.
  • Bare claude "..." hangs in CI. Without -p, the command launches the interactive REPL and waits forever in a non-interactive pipeline. Every scripted invocation needs -p.
  • Shift+Enter inserts nothing. Multiline input requires terminal key bindings; run /terminal-setup once. Until then, paste multiline prompts or wrap them in quotes on the command line.

With command-line mastery achieved, you’re ready to tackle large, complex codebases. Continue to Large Codebase Management to learn strategies for enterprise-scale development.