Claude Code’s headless mode enables you to integrate AI-powered development assistance directly into your scripts, CI/CD pipelines, and automation workflows. This article explores practical use cases with example prompts to maximize your productivity.
Headless mode allows you to run Claude Code programmatically without the interactive CLI interface, making it perfect for automation scenarios. The primary interface uses the claude
command with the -p
or --print
flag for non-interactive execution.
1
2
3
4
5
|
# Install Claude Code
npm install -g @anthropic/claude-code
# Set up your API key
export ANTHROPIC_API_KEY=your_api_key_here
|
The core syntax for headless mode uses the -p
flag:
1
|
claude -p "Your prompt here"
|
Control output format with --output-format
:
text
(default): Human-readable output
json
: Structured JSON with metadata
stream-json
: Real-time JSON streaming
1
2
3
4
5
|
# Get JSON output with metadata
claude -p "Review this file" --output-format json
# Stream JSON for real-time processing
claude -p "Long running task" --output-format stream-json
|
1. Infrastructure Monitoring & Analytics
Link to heading
Automated system analysis and intelligent alerting:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# Analyze system logs for anomalies
claude -p "Analyze the last 1000 lines of /var/log/nginx/access.log \
and identify unusual traffic patterns or potential security threats" \
--allowedTools "Read,Grep"
# Generate infrastructure health reports
claude -p "Create a comprehensive health report based on CPU, memory, \
and disk usage metrics in the monitoring dashboard" \
--output-format json
# Predictive maintenance alerts
claude -p "Based on recent performance metrics, predict potential \
system bottlenecks and suggest preventive actions"
|
2. Business Intelligence Automation
Link to heading
Transform data into actionable insights:
1
2
3
4
5
6
7
8
9
10
11
|
# Daily KPI analysis
claude -p "Analyze yesterday's sales data and generate executive \
summary with trends and recommendations" --output-format json
# Competitive intelligence reports
claude -p "Review competitor pricing updates from scraped data \
and suggest pricing strategy adjustments"
# Customer behavior analysis
claude -p "Process user interaction logs and identify friction \
points in the customer journey"
|
Automated content management and optimization:
1
2
3
4
5
6
7
8
9
10
11
12
|
# SEO content optimization
claude -p "Review and optimize website content in the /content \
directory for SEO best practices and readability" \
--allowedTools "Read,Edit"
# Social media automation
claude -p "Generate social media content calendar based on recent \
blog posts and company announcements" --output-format json
# Image and asset analysis
claude -p "Audit all images in /assets for accessibility, \
optimization, and compliance with brand guidelines"
|
4. Legal & Compliance Automation
Link to heading
Streamline regulatory and legal processes:
1
2
3
4
5
6
7
8
9
10
11
|
# Contract analysis
claude -p "Review vendor contracts in /legal/contracts and flag \
potential risk clauses or compliance issues" \
--allowedTools "Read,Grep"
# Privacy policy updates
claude -p "Update privacy policy to reflect new data collection \
practices while maintaining GDPR compliance"
# Audit trail generation
claude -p "Generate compliance audit report based on system logs and user activity data" --output-format json
|
5. DevOps & Deployment Intelligence
Link to heading
Smart deployment and infrastructure management:
1
2
3
4
5
6
7
8
9
10
|
# Deployment risk assessment
claude -p "Analyze the planned deployment changes and assess \
potential risks, suggesting rollback strategies"
# Infrastructure cost optimization
claude -p "Review cloud resource usage patterns and recommend cost optimization strategies" --output-format json
# Incident response automation
claude -p "Based on current system alerts, prioritize issues \
and generate incident response playbook"
|
Proactive security monitoring and response:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# Comprehensive security audit with automatic issue creation
claude --model opus -p "I would like you to find high and critical \
security issues in this codebase. Create the issues on github directly. \
Please avoid false positives and use descriptive title and descriptions" \
--allowedTools "Bash"
# Security log analysis
claude -p "Analyze security logs for the past 24 hours and identify \
potential threats or breach attempts" --allowedTools "Read,Grep"
# Vulnerability assessment
claude -p "Review recent dependency updates and assess security \
implications with mitigation strategies"
# Access pattern analysis
claude -p "Analyze user access patterns and flag suspicious login \
activities or privilege escalations"
|
7. Data Pipeline & ETL Automation
Link to heading
Intelligent data processing and quality assurance:
1
2
3
4
5
6
7
8
9
10
|
# Data quality assessment
claude -p "Analyze data quality in the user database and identify \
inconsistencies or missing critical information"
# ETL process optimization
claude -p "Review data transformation scripts and suggest \
performance improvements and error handling"
# Data lineage documentation
claude -p "Generate documentation for data flow from source systems to analytics warehouse" --output-format json
|
8. Customer Support Intelligence
Link to heading
Enhance support operations with AI insights:
1
2
3
4
5
6
7
8
9
10
11
|
# Support ticket analysis
claude -p "Analyze support tickets from the past week and identify \
common issues and resolution patterns"
# Knowledge base optimization
claude -p "Review support documentation and suggest improvements \
based on recent customer queries"
# Escalation prediction
claude -p "Based on ticket content and customer history, predict \
which issues might require escalation"
|
Continue multi-turn conversations using --resume
:
1
2
3
4
5
|
# Start a session
SESSION_ID=$(claude -p "Start code review" --output-format json | jq -r '.sessionId')
# Continue the conversation
claude -p "Focus on security issues" --resume $SESSION_ID
|
Restrict available tools with --allowedTools
:
1
2
3
4
5
6
|
# Only allow read operations
claude -p "Review the codebase" --allowedTools "Read,Grep,Glob"
# Custom system prompt for specialized behavior
claude -p "Review for accessibility" \
--append-system-prompt "Focus specifically on WCAG compliance"
|
Best Practices for Headless Mode
Link to heading
1. Use JSON Output for Automation
Link to heading
JSON output provides metadata including cost, duration, and session IDs:
1
2
3
4
|
# Parse results programmatically
RESULT=$(claude -p "Check test coverage" --output-format json)
echo $RESULT | jq '.content' # Get the response
echo $RESULT | jq '.cost' # Get cost information
|
1
2
3
4
5
6
|
# Error handling example
if ! claude -p "Run tests and fix failures" --output-format json > result.json 2>&1; then
echo "Claude Code execution failed"
cat result.json
exit 1
fi
|
3. Streaming for Long Operations
Link to heading
Use stream-json for real-time feedback on long-running tasks:
1
2
3
|
claude -p "Refactor large codebase" --output-format stream-json | while read line; do
echo "Progress: $line"
done
|
GitHub Actions - Business Intelligence
Link to heading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
name: Daily Business Analytics
on:
schedule:
- cron: '0 8 * * *' # Run at 8 AM daily
jobs:
business-insights:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Generate Business Insights
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
DATE=$(date +%Y-%m-%d)
claude -p "Analyze yesterday's business metrics and generate \
executive summary with actionable insights" \
--output-format json > insights-$DATE.json
# Send alert if revenue dropped significantly
ALERT=$(jq -r '.alerts.revenue' insights-$DATE.json)
if [[ "$ALERT" == "critical" ]]; then
echo "Revenue alert detected" >> $GITHUB_STEP_SUMMARY
fi
|
Pre-commit Hook - Content Compliance
Link to heading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/bin/sh
# .git/hooks/pre-commit
# Check content changes for compliance issues
git diff --cached --name-only | grep -E '\.(md|txt|html)$' | while read file; do
claude -p "Review $file for brand compliance, legal risks, and content quality" \
--allowedTools "Read" \
--output-format json > "/tmp/compliance-$file.json"
RISK=$(jq -r '.risk_level' "/tmp/compliance-$file.json")
if [[ "$RISK" == "high" ]]; then
echo "ERROR: High-risk content detected in $file"
exit 1
fi
done
|
Cron Job - Infrastructure Monitoring
Link to heading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# /etc/cron.d/infrastructure-health
# Run infrastructure health checks every hour
0 * * * * root /usr/local/bin/infrastructure-monitor.sh
#!/bin/bash
# infrastructure-monitor.sh
claude -p "Analyze system performance metrics and generate health \
report with predictive maintenance recommendations" \
--output-format json --allowedTools "Read,Bash" > \
"/var/log/health-$(date +%H).json"
# Check for critical issues
CRITICAL=$(jq -r '.critical_issues' "/var/log/health-$(date +%H).json")
if [[ "$CRITICAL" != "null" ]]; then
echo "$CRITICAL" | mail -s "Infrastructure Alert" ops@company.com
fi
|
Process multiple files or directories:
1
2
3
4
5
6
7
|
# Review multiple components
claude -p "Review all React components in src/components/ for accessibility compliance"
# Batch refactoring with controlled tools
claude -p "Refactor all utility functions to use consistent naming \
conventions and add proper error handling" \
--allowedTools "Read,Edit,MultiEdit"
|
Create complex, conversation-based workflows:
1
2
3
4
5
6
7
8
9
10
11
|
# Start a feature implementation session
SESSION_ID=$(claude -p "Plan implementation of user authentication feature" --output-format json | jq -r '.sessionId')
# Continue with database models
claude -p "Now implement the database models" --resume $SESSION_ID
# Add API endpoints
claude -p "Create the API endpoints" --resume $SESSION_ID
# Finalize with tests
claude -p "Generate comprehensive tests for the authentication flow" --resume $SESSION_ID
|
Business Intelligence Dashboard
Link to heading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/bin/bash
# daily-insights.sh
DATE=$(date +%Y-%m-%d)
# Generate daily business insights
claude -p "Analyze sales data from $DATE and create executive \
dashboard with KPIs, trends, and recommendations" \
--output-format json --allowedTools "Read,Grep" > \
reports/daily-insights-$DATE.json
# Extract key metrics for alerts
REVENUE=$(jq '.revenue_trend' reports/daily-insights-$DATE.json)
if [[ "$REVENUE" == *"declining"* ]]; then
echo "ALERT: Revenue declining trend detected" | mail -s "Business Alert" executives@company.com
fi
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/bin/bash
# cost-optimizer.sh
# Analyze cloud usage and suggest optimizations
claude -p "Review AWS usage patterns from CloudWatch metrics \
and recommend cost optimization strategies" \
--output-format stream-json --allowedTools "Read,Bash" | \
while read line; do
echo "$(date): $line" >> cost-analysis.log
# Check for urgent recommendations
if echo "$line" | grep -q "URGENT"; then
echo "$line" | mail -s "Urgent Cost Alert" devops@company.com
fi
done
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/bin/bash
# compliance-check.sh
# Automated content review for legal and brand compliance
find ./content -name "*.md" -type f | while read file; do
claude -p "Review content in $file for GDPR compliance, brand \
guidelines, and legal risks" --allowedTools "Read" \
--output-format json > \
"compliance-reports/$(basename $file .md)-compliance.json"
# Flag high-risk content
RISK_LEVEL=$(jq -r '.risk_assessment.level' "compliance-reports/$(basename $file .md)-compliance.json")
if [[ "$RISK_LEVEL" == "high" ]]; then
echo "High-risk content detected in $file" >> compliance-alerts.log
fi
done
|
1
2
|
# Handle timeouts gracefully
timeout 300 claude -p "Long running analysis" || echo "Task timed out"
|
1
2
3
4
5
6
7
8
|
# Track costs across multiple operations
TOTAL_COST=0
for task in review test docs; do
RESULT=$(claude -p "$task workflow" --output-format json)
COST=$(echo "$RESULT" | jq '.cost.total')
TOTAL_COST=$(echo "$TOTAL_COST + $COST" | bc)
done
echo "Total cost: $TOTAL_COST"
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# Robust error handling
run_claude_task() {
local prompt="$1"
local max_retries=3
local retry=0
while [ $retry -lt $max_retries ]; do
if claude -p "$prompt" --output-format json > result.json 2>&1; then
return 0
fi
retry=$((retry + 1))
echo "Retry $retry/$max_retries after failure"
sleep 5
done
return 1
}
|
Claude Code’s headless mode transforms development workflows through programmatic AI assistance. The key benefits include:
- Automation: Integrate AI into CI/CD pipelines and scripts
- Consistency: Standardize code reviews and quality checks
- Efficiency: Batch process multiple files and complex workflows
- Flexibility: Control tools and output formats for specific needs
Start with simple automation tasks and gradually build more sophisticated workflows as you explore the tool’s capabilities.