Headless Mode Beginner
Headless mode allows you to use Claude Code without an interactive session. Using the -p flag, piping, and output formatting, you can integrate Claude Code into scripts, cron jobs, and automation workflows.
The -p (Prompt) Flag
The -p flag is the gateway to non-interactive Claude Code. It sends a single prompt, waits for the response, and exits:
# Basic one-shot usage $ claude -p "What files are in the src/ directory?" # With a specific task $ claude -p "Add input validation to the signup form in src/components/SignupForm.tsx" # Quick code generation $ claude -p "Generate a Python function to validate email addresses"
Piping Input to Claude
You can pipe data into Claude Code using standard Unix pipes. This is powerful for feeding context from other commands:
# Pipe file contents for review $ cat src/auth.js | claude -p "Review this code for security vulnerabilities" # Pipe error logs for analysis $ tail -100 /var/log/app/error.log | claude -p "What's causing these errors?" # Pipe test output $ npm test 2>&1 | claude -p "Analyze the test failures and suggest fixes" # Pipe git diff $ git diff --staged | claude -p "Write a commit message for these changes" # Use echo for quick prompts $ echo "fix the login bug" | claude
Output Formats
Control the output format for better integration with other tools:
# Default text output $ claude -p "List all API endpoints" # JSON output for programmatic parsing $ claude -p "List all API endpoints" --output-format json # Stream output in JSON format $ claude -p "Refactor the database module" --output-format stream-json # Parse JSON output with jq $ claude -p "Analyze code complexity" --output-format json | jq '.result'
Exit Codes
Claude Code returns meaningful exit codes that you can use in scripts:
| Exit Code | Meaning | Use in Scripts |
|---|---|---|
0 |
Success — Claude completed the task | Continue to next step |
1 |
General error — something went wrong | Log error and alert |
2 |
Invalid arguments or configuration | Check command syntax |
#!/bin/bash # Use exit codes in scripts claude -p "Fix the failing tests in src/utils/" if [ $? -eq 0 ]; then echo "Claude successfully fixed the tests" npm test else echo "Claude encountered an error" exit 1 fi
Scripting with Claude Code
Build automation scripts that leverage Claude Code for intelligent processing:
#!/bin/bash # Script: auto-review.sh # Automatically review all changed files for file in $(git diff --name-only HEAD~1); do echo "Reviewing: $file" claude -p "Review this file for bugs and improvements: $file" >> review-report.txt echo "---" >> review-report.txt done echo "Review complete. See review-report.txt"
Batch Processing Files
Process multiple files in sequence or parallel with Claude Code:
#!/bin/bash # Add JSDoc comments to all JavaScript files find src/ -name "*.js" | while read file; do echo "Processing: $file" claude -p "Add JSDoc comments to all exported functions in $file" done # Process files in parallel (use with caution - API rate limits) find src/ -name "*.ts" | xargs -P 3 -I {} claude -p "Add TypeScript type annotations to {}"
Cron Jobs with Claude
Schedule recurring tasks with cron:
# crontab -e # Daily code health check at 6 AM 0 6 * * * cd /home/user/project && claude -p "Run a code health check: look for unused imports, dead code, and potential bugs" > /tmp/daily-report.txt 2>&1 # Weekly dependency audit on Mondays 0 9 * * 1 cd /home/user/project && claude -p "Check for outdated dependencies and security vulnerabilities" > /tmp/weekly-audit.txt 2>&1 # Generate changelog every Friday 0 17 * * 5 cd /home/user/project && git log --since='1 week ago' --oneline | claude -p "Generate a changelog from these commits" >> CHANGELOG.md
Complete Automation Script Example
Here is a complete script that demonstrates several headless patterns together:
#!/bin/bash # smart-deploy.sh - AI-assisted deployment script set -e PROJECT_DIR="/home/user/my-app" cd "$PROJECT_DIR" # Step 1: Pre-deployment check echo "Running pre-deployment analysis..." ANALYSIS=$(claude -p "Analyze the current git diff against main. Are there any risky changes that could break production?" --output-format json) # Step 2: Run tests echo "Running tests..." TEST_OUTPUT=$(npm test 2>&1) || { echo "Tests failed. Asking Claude for help..." echo "$TEST_OUTPUT" | claude -p "These tests failed. Fix them." npm test || exit 1 } # Step 3: Generate release notes echo "Generating release notes..." git log --since="last week" --oneline | claude -p "Generate professional release notes from these commits" > RELEASE_NOTES.md echo "Deployment preparation complete!"
--max-turns flag to limit how many actions Claude takes per invocation.
Try It Yourself
Create a simple script that uses claude -p to analyze your latest git commit and generate a summary. In the next lesson, you will learn how to use Claude Code over SSH connections.
Lilly Tech Systems