Skip to content

CLI Power User Guide

Master advanced Claude Code CLI techniques for maximum productivity.

What You'll Learn

  • Advanced CLI flags and options
  • Shell integration patterns
  • Scripting and automation
  • Session management
  • Performance optimization
  • Expert workflows

Complete CLI Reference

All Command-Line Options

claude [options] [initial-prompt]

Options:
  -c, --continue         Resume previous conversation
  -p, --print           Non-interactive mode (print and exit)
  --cwd <directory>      Set working directory
  --model <model>        Override default model
  --max-tokens <n>       Limit response tokens
  --system <prompt>      Custom system prompt
  --allowedTools <t>     Comma-separated allowed tools
  --version              Show version number
  --help                 Show help

Examples:
  claude                          # Start interactive session
  claude "explain this code"      # Start with prompt
  claude -c                       # Continue last session
  claude -p "what is this?"       # Non-interactive
  claude --cwd /project "help"    # Different directory

Non-Interactive Mode Deep Dive

The -p (print) flag is your key to automation:

# Basic usage
claude -p "What testing framework does this project use?"

# Capture output
ANSWER=$(claude -p "What is the main entry point?")
echo "Entry point: $ANSWER"

# Pipe input
cat error.log | claude -p "Analyze these errors"

# Pipe output
claude -p "Generate a README for this project" > README.md

# Combine with other tools
find . -name "*.ts" | head -20 | claude -p "What do these TypeScript files do?"

# Exit codes for scripting
claude -p "Are there any TODO comments in src/?" && echo "Found TODOs"

Working Directory Control

# Work in different directory without cd
claude --cwd /path/to/project "Run the tests"

# Multiple projects
claude --cwd ~/project-a "List API routes"
claude --cwd ~/project-b "List API routes"

# In scripts
for project in ~/projects/*/; do
  echo "=== $project ==="
  claude --cwd "$project" -p "What framework is this?"
done

Shell Integration Mastery

Advanced Aliases

# ~/.zshrc or ~/.bashrc

# Core aliases
alias cc="claude"
alias ccc="claude --continue"
alias ccp="claude -p"

# Project-specific Claude
alias cc-web="claude --cwd ~/projects/web-app"
alias cc-api="claude --cwd ~/projects/api"
alias cc-mobile="claude --cwd ~/projects/mobile"

# Common tasks
alias cc-review="claude 'Review recent git changes for issues'"
alias cc-test="claude 'Run tests and explain any failures'"
alias cc-docs="claude 'What is missing from the documentation?'"
alias cc-todo="claude 'Find all TODO and FIXME comments'"
alias cc-security="claude 'Scan for security vulnerabilities'"

# Git integration
alias cc-commit="claude 'Create a commit with appropriate message'"
alias cc-pr="claude 'Create a pull request with summary'"
alias cc-diff="git diff | claude -p 'Review this diff'"

# Quick answers
cc-ask() { claude -p "$*"; }
cc-explain() { claude -p "Explain: $*"; }
cc-how() { claude -p "How do I $* in this project?"; }

Shell Functions

# Analyze a file
cc-file() {
  if [ -f "$1" ]; then
    claude "Analyze this file: $1"
  else
    echo "File not found: $1"
    return 1
  fi
}

# Review specific files
cc-review-files() {
  claude "Review these files for issues: $*"
}

# Create a new feature
cc-feature() {
  local name="$1"
  shift
  claude "Create a new feature called '$name'. Requirements: $*"
}

# Debug with context
cc-debug() {
  local error="$1"
  local file="$2"
  claude "Debug this error in $file: $error"
}

# Quick test
cc-test-file() {
  claude "Write tests for $1 following existing patterns"
}

# Generate based on example
cc-like() {
  local example="$1"
  local new="$2"
  claude "Create $new following the same pattern as $example"
}

FZF Integration

# Fuzzy select file and analyze with Claude
cc-fzf() {
  local file=$(fzf --preview 'cat {}')
  if [ -n "$file" ]; then
    claude "Analyze: $file"
  fi
}

# Select from recent files
cc-recent() {
  local file=$(find . -type f -mmin -60 | fzf)
  if [ -n "$file" ]; then
    claude "What changed recently in $file?"
  fi
}

# Select and explain function
cc-function() {
  local match=$(rg -n "function|def |const .* = " --type-add 'code:*.{js,ts,py}' -t code | fzf)
  if [ -n "$match" ]; then
    local file=$(echo "$match" | cut -d: -f1)
    local line=$(echo "$match" | cut -d: -f2)
    claude "Explain the function at line $line in $file"
  fi
}

Scripting Patterns

Build Script Integration

#!/bin/bash
# build-with-ai.sh - AI-assisted build process

set -e

echo "🔍 Pre-build analysis..."
ISSUES=$(claude -p "Quick check: any obvious issues in src/ that would break the build?")
if [[ "$ISSUES" == *"issue"* ]] || [[ "$ISSUES" == *"error"* ]]; then
  echo "⚠️  Potential issues found:"
  echo "$ISSUES"
  read -p "Continue anyway? (y/n) " -n 1 -r
  echo
  [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
fi

echo "🔨 Building..."
if ! npm run build 2>&1 | tee build.log; then
  echo "❌ Build failed. Analyzing..."
  claude -p "Analyze this build failure and suggest fixes: $(cat build.log | tail -50)"
  exit 1
fi

echo "✅ Build successful!"

Test Runner Enhancement

#!/bin/bash
# smart-test.sh - Run tests with AI analysis

run_tests() {
  npm test 2>&1 | tee test-output.log
  return ${PIPESTATUS[0]}
}

if run_tests; then
  echo "✅ All tests passed"
else
  echo "❌ Tests failed. Getting AI analysis..."

  ANALYSIS=$(claude -p "Analyze these test failures concisely:
$(cat test-output.log | tail -100)

For each failure:
1. Likely cause
2. Suggested fix (one line)")

  echo ""
  echo "📋 Analysis:"
  echo "$ANALYSIS"

  read -p "Would you like Claude to attempt fixes? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    claude "Fix the test failures shown in test-output.log"
  fi
fi

Deployment Helper

#!/bin/bash
# deploy.sh - AI-assisted deployment

ENV=${1:-staging}

echo "🚀 Deploying to $ENV..."

# Pre-deploy checks
echo "Running pre-deploy analysis..."
READY=$(claude -p "Is this codebase ready for $ENV deployment? Check for:
1. Debug code or console.logs
2. TODO comments in critical paths
3. Hardcoded credentials
4. Missing error handling
Reply READY or list issues.")

if [[ "$READY" != *"READY"* ]]; then
  echo "⚠️  Not ready for deployment:"
  echo "$READY"
  exit 1
fi

# Deploy
./actual-deploy-script.sh $ENV
DEPLOY_STATUS=$?

# Post-deploy notification
if [ $DEPLOY_STATUS -eq 0 ]; then
  claude -p "Generate a deployment summary for Slack:
  - Environment: $ENV
  - Branch: $(git branch --show-current)
  - Commit: $(git log -1 --format='%h %s')
  - Time: $(date)"
else
  claude -p "Deployment to $ENV failed. Generate an incident report based on the last 50 lines of deployment logs."
fi

PR Description Generator

#!/bin/bash
# pr-describe.sh - Generate PR description

BRANCH=$(git branch --show-current)
BASE=${1:-main}

# Get changes
COMMITS=$(git log $BASE..HEAD --oneline)
DIFF_STAT=$(git diff $BASE..HEAD --stat)
CHANGED_FILES=$(git diff $BASE..HEAD --name-only)

# Generate description
claude -p "Generate a pull request description:

Branch: $BRANCH -> $BASE

Commits:
$COMMITS

Changed files:
$CHANGED_FILES

Diff stats:
$DIFF_STAT

Format:
## Summary
[2-3 bullet points]

## Changes
[list of main changes]

## Testing
[how to test]

## Checklist
- [ ] Tests pass
- [ ] Lint passes
- [ ] Documentation updated (if needed)"

Session Management

Conversation Continuity

# Start a focused session
claude "I'm working on the authentication module today. Let's focus on that."

# Later, continue where you left off
claude -c

# Or start fresh if context is polluted
claude  # New session

Context Compaction

# Inside a long session
> /compact

# Claude summarizes key context and continues

Multiple Sessions Strategy

# Use tmux/screen for multiple focused sessions
tmux new-session -s claude-auth
# In this session: only auth-related work

# Another terminal
tmux new-session -s claude-frontend
# In this session: only frontend work

Performance Optimization

Efficient Prompting

# Inefficient: Multiple round trips
claude -p "What framework is this?"
claude -p "What database?"
claude -p "What is the API structure?"

# Efficient: Single comprehensive request
claude -p "Give me a quick overview: framework, database, API structure"

Model Selection

# Quick questions: Use faster model
claude --model claude-haiku "What's in package.json?"

# Complex tasks: Use capable model
claude --model claude-sonnet "Refactor this module for better testability"

# Critical analysis: Use best model
claude --model claude-opus "Security audit the authentication flow"

Token Management

# Limit output for quick answers
claude -p --max-tokens 100 "What test framework is used?"

# Full output for detailed work
claude -p --max-tokens 4000 "Explain the entire auth flow"

Advanced Automation

Cron Jobs

# Daily code health check
0 9 * * * cd /project && claude -p "Quick health check: any obvious issues?" >> /var/log/claude-health.log 2>&1

# Weekly dependency check
0 10 * * 1 cd /project && claude -p "Any critical dependency updates needed?" | mail -s "Weekly Deps" team@company.com

# Pre-commit style check (in .git/hooks/pre-commit)
claude -p "Check staged files for style issues" || exit 0  # Don't block commit

CI/CD Integration

# GitHub Actions example
- name: AI Code Review
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: |
    npm install -g @anthropic-ai/claude-code
    REVIEW=$(claude -p "Review this PR diff for issues: $(git diff origin/main...HEAD)")
    echo "review<<EOF" >> $GITHUB_OUTPUT
    echo "$REVIEW" >> $GITHUB_OUTPUT
    echo "EOF" >> $GITHUB_OUTPUT

- name: Comment PR
  uses: actions/github-script@v6
  with:
    script: |
      github.rest.issues.createComment({
        owner: context.repo.owner,
        repo: context.repo.repo,
        issue_number: context.issue.number,
        body: `## AI Review\n${{ steps.review.outputs.review }}`
      })

Webhook Handler

#!/bin/bash
# webhook-handler.sh - Handle GitHub webhooks with Claude analysis

# Parse webhook payload
EVENT_TYPE=$(echo "$WEBHOOK_PAYLOAD" | jq -r '.action')
REPO=$(echo "$WEBHOOK_PAYLOAD" | jq -r '.repository.name')

case "$EVENT_TYPE" in
  "opened")
    # New issue - suggest labels and assignees
    ISSUE_BODY=$(echo "$WEBHOOK_PAYLOAD" | jq -r '.issue.body')
    claude -p "Analyze this issue and suggest labels and assignees: $ISSUE_BODY"
    ;;
  "created")
    # New comment - check if question and suggest answer
    COMMENT=$(echo "$WEBHOOK_PAYLOAD" | jq -r '.comment.body')
    claude -p "Is this a question that can be answered from the codebase? $COMMENT"
    ;;
esac

Expert Workflows

Workflow 1: Full Feature Development

# 1. Plan the feature
claude "I need to add user authentication. Let's plan the implementation."

# 2. Create the structure
> Create the file structure and interfaces first

# 3. Implement with TDD
> Let's implement with TDD. Start with the tests.

# 4. Review before commit
> Review all our changes for issues

# 5. Generate commit and PR
> Create a detailed commit message
> Help me create the PR description

Workflow 2: Bug Investigation

# 1. Start investigation
claude "Bug: Users report intermittent 500 errors on checkout. Let's investigate."

# 2. Gather evidence
> Show me the checkout-related code
> What does the error logging show?

# 3. Form hypotheses
> Based on this, what are the likely causes?

# 4. Test hypotheses
> Let's add logging to verify hypothesis #1

# 5. Fix and verify
> Implement the fix
> Write a test that would have caught this

Workflow 3: Codebase Onboarding

# New developer quick start
claude "I'm new to this codebase. Give me a quick orientation."

> What's the tech stack?
> What are the key files to understand?
> How do I run it locally?
> What are the main patterns used?
> What should I know before making changes?

Quick Reference Card

┌─────────────────────────────────────────────────────────────────┐
│             CLAUDE CODE CLI POWER USER REFERENCE                 │
├─────────────────────────────────────────────────────────────────┤
│ INVOCATION                                                       │
│   claude                    Interactive session                  │
│   claude "prompt"           Start with prompt                    │
│   claude -c                 Continue previous session            │
│   claude -p "prompt"        Non-interactive (for scripts)        │
│   claude --cwd DIR          Work in different directory          │
│   claude --model MODEL      Use specific model                   │
├─────────────────────────────────────────────────────────────────┤
│ SCRIPTING                                                        │
│   OUTPUT=$(claude -p "q")   Capture output                       │
│   cat file | claude -p "q"  Pipe input                           │
│   claude -p "q" > file      Pipe output                          │
│   claude -p "q" && echo ok  Use exit code                        │
├─────────────────────────────────────────────────────────────────┤
│ SESSION COMMANDS                                                 │
│   /help                     Show commands                        │
│   /compact                  Compress conversation                │
│   /clear                    Clear history                        │
│   /exit                     Exit session                         │
├─────────────────────────────────────────────────────────────────┤
│ KEYBOARD                                                         │
│   Ctrl+C                    Cancel / Exit (2x)                   │
│   Shift+Enter               Multiline input                      │
│   Up/Down                   History navigation                   │
│   Ctrl+L                    Clear screen                         │
└─────────────────────────────────────────────────────────────────┘

What's Next?

You've completed the expert tutorials! Return to the main guide or explore the exercises.


Summary: - Master -p for scripting and automation - Use --cwd to work across multiple projects - Create aliases and functions for common tasks - Integrate with fzf, git, and other CLI tools - Build CI/CD pipelines with Claude CLI - Use appropriate models for different tasks - Optimize token usage with focused prompts - Chain commands with pipes and scripts


Learning Resources

NetworkChuck: AI in the Terminal - Power User (3.6M subscribers)

Master CLI techniques - scripting, aliases, shell integration, and CI/CD pipelines.

Additional Resources

Type Resource Description
🎬 Video 800+ Hours CLI Tips Edmund Yong - Power user secrets
📚 Official Docs CLI Reference Complete CLI documentation
📖 Tutorial AI Terminal Guide Advanced CLI techniques
🎓 Free Course Awesome Claude Code Scripts and aliases collection
💼 Commercial AI CLI Course CLI automation mastery