What Is Claude Code Headless Mode? How to Run AI Agents Without a Terminal
Claude Code headless mode uses the -p flag to run agents autonomously on a schedule. Learn how to set it up with cron jobs for fully automated workflows.
Running Claude Code Without Anyone Watching
Most people use Claude Code the way you’d use any coding assistant — you open a terminal, type a prompt, and wait for a response. It’s interactive. You’re in the loop for every decision.
But there’s another way to run Claude Code that most developers haven’t fully explored: headless mode. This is how you use Claude Code as part of a fully automated pipeline — no terminal open, no one waiting at the keyboard, no interactive session required. You just set it up and let it run.
Claude Code headless mode uses the -p flag to accept a prompt directly from the command line and execute without any user interaction. That makes it suitable for automation, scheduled tasks, and multi-agent workflows where human input isn’t available — or isn’t wanted.
This guide covers exactly what headless mode is, how the -p flag works, how to schedule Claude Code agents with cron, and what you can realistically build with this approach.
What Headless Mode Actually Means
“Headless” is a term borrowed from browser automation. A headless browser (like Puppeteer running Chrome without a window) does everything a normal browser does — renders pages, runs JavaScript, handles requests — but without a visible UI that a user interacts with.
Claude Code headless mode follows the same logic. Instead of running interactively where you type prompts and read responses in real time, you pass the prompt as a flag at invocation, Claude runs the task, and the output is returned to stdout. The process exits when the task is done.
This is the difference between a tool you use and a tool that runs as part of a system.
The -p Flag
The core mechanic is simple. In normal mode, you’d run:
claude
And Claude Code opens an interactive session. In headless mode, you pass the prompt directly:
claude -p "Review the last 10 git commits and summarize any breaking changes"
Claude processes the prompt, executes any necessary tool calls (reading files, running commands, checking git history), and outputs the result to stdout. Then it exits.
That output can be piped to other commands, written to a file, sent to a webhook, logged, or used however your automation needs it.
Why This Matters for Automation
Interactive sessions are stateful and human-paced. Headless mode is stateless and machine-paced.
When Claude runs with -p, it:
- Reads the prompt from the flag
- Executes the task using whatever tools are available
- Returns output to stdout
- Exits cleanly with a status code
This behavior is predictable and composable. It’s the difference between a UI you click and a function you call.
Setting Up Claude Code for Headless Use
Before you can run Claude Code headlessly, a few things need to be in place.
Prerequisites
Claude Code installed globally. Claude Code is an npm package, so you install it with:
npm install -g @anthropic-ai/claude-code
Authentication configured. Claude Code needs a valid Anthropic API key. You can set this in your environment:
export ANTHROPIC_API_KEY=your_key_here
For automation contexts like cron jobs or CI pipelines, this environment variable needs to be available in the execution environment — not just your interactive shell session. More on that in the cron setup section.
A working directory. Claude Code operates relative to a directory. When running headlessly, you’ll often want to specify exactly where it should work:
claude -p "Check for any TODO comments and output a list" --directory /path/to/your/project
Output Format Options
By default, Claude Code streams output to the terminal as it generates it. In headless mode, you often want structured output that’s easy to parse.
The --output-format flag gives you options:
claude -p "Analyze this file and return a JSON summary" --output-format json
Using JSON or text output formats is useful when the output feeds into another system. You can also pipe output:
claude -p "List all functions with no docstrings" > undocumented_functions.txt
Or combine it with other CLI tools:
claude -p "Find all hardcoded API keys in this codebase" | grep -i "key"
Disabling Confirmations
In interactive mode, Claude Code sometimes pauses to confirm before taking certain actions — running a shell command, editing a file, and so on. In headless mode, that would block indefinitely with no one to confirm.
The --dangerously-skip-permissions flag skips those prompts. Use it carefully — it removes guardrails that exist for good reason.
claude -p "Run the test suite and fix any failing tests" --dangerously-skip-permissions
Only use this when:
- You fully understand what task you’re giving Claude
- The execution environment is isolated (a container, a CI runner, a sandboxed repo)
- You’ve tested the prompt interactively first and know what it does
For most automation, you’ll want to design prompts that don’t require dangerous permissions in the first place — stick to read operations and staged outputs where possible.
Scheduling Claude Code with Cron Jobs
Once you have headless mode working from the command line, the next step is scheduling it. Cron is the simplest way to do this on any Unix-based system (Linux, macOS, most servers).
How Cron Works
Cron is a time-based job scheduler built into Unix. You define a schedule and a command, and the system runs it automatically. You manage cron jobs by editing the crontab file:
crontab -e
The format for each line is:
minute hour day month weekday command
So 0 9 * * 1-5 /path/to/command means “run at 9:00 AM, Monday through Friday.”
Setting Up a Claude Code Cron Job
Here’s a basic example that runs a daily code review summary every morning at 8 AM:
0 8 * * * /usr/bin/env bash -c 'export ANTHROPIC_API_KEY=your_key; cd /path/to/project && claude -p "Summarize what changed in git since yesterday and flag anything that looks risky" >> /var/log/daily_review.log 2>&1'
A few things to note in this setup:
Use full paths. Cron runs with a minimal environment — it doesn’t load your shell profile, so commands like claude may not be on the PATH. Either use the full path to the binary (find it with which claude) or source your profile explicitly.
Set environment variables explicitly. Cron won’t have your ANTHROPIC_API_KEY unless you set it. You can set it in the crontab directly (less secure) or load it from a file:
0 8 * * * /usr/bin/env bash -c 'source /home/user/.env && cd /path/to/project && claude -p "your prompt here" >> /var/log/claude.log 2>&1'
Redirect output. The >> /var/log/claude.log 2>&1 part sends both stdout and stderr to a log file. Without this, you get no record of what happened.
Test manually first. Before scheduling, run the exact command from the terminal (with the full paths) to make sure it works. Debug there, then add to cron.
More Scheduling Patterns
Every hour during business hours:
0 9-17 * * 1-5 /usr/bin/env bash -c 'source /home/user/.env && cd /repo && claude -p "Check for new errors in the application logs" >> /var/log/hourly_check.log 2>&1'
Every 15 minutes:
*/15 * * * * /usr/bin/env bash -c 'source /home/user/.env && cd /repo && claude -p "Monitor the build status and alert if anything fails" >> /var/log/build_monitor.log 2>&1'
Weekly codebase health check on Monday mornings:
0 7 * * 1 /usr/bin/env bash -c 'source /home/user/.env && cd /repo && claude -p "Run a comprehensive review of code quality, test coverage gaps, and documentation status. Output a markdown report." > /reports/weekly_$(date +\%Y\%m\%d).md 2>&1'
Using Systemd Timers as an Alternative
On modern Linux systems, systemd timers are often a better option than cron. They offer:
- Better logging (via journald)
- Dependency management (wait for network, etc.)
- More reliable execution on systems that don’t run 24/7
The tradeoff is more configuration files. For simple use cases, cron is still fine.
Practical Use Cases for Claude Code Headless Mode
Headless mode opens up a category of tasks that would be tedious or impractical to do manually on a schedule. Here are the most useful patterns.
Automated Code Review
Run Claude against every pull request or after every push to flag issues before a human reviews:
claude -p "Review the diff in the last commit. Check for security issues, poor error handling, and missing tests. Output a structured report." --output-format json
This doesn’t replace human review — it catches obvious issues and surfaces them quickly, so human reviewers can focus on higher-level concerns.
Dependency and Security Monitoring
Schedule a weekly scan of your dependencies for known vulnerabilities:
claude -p "Run npm audit, analyze the output, and create a prioritized list of issues to fix. Flag any critical severity findings."
Log Analysis
Application logs contain a lot of signal that’s easy to miss when you’re not actively looking. Schedule Claude to summarize them:
claude -p "Analyze the application logs from the last 24 hours. Identify error patterns, unusual activity, and any performance degradation. Summarize in bullet points."
Documentation Maintenance
Keeping docs in sync with code is one of those tasks that always falls behind. Automate the check:
claude -p "Compare the README and API docs against the current codebase. List anything that's outdated or missing."
Test Coverage Analysis
Run after your test suite completes as part of CI:
claude -p "Review the test coverage report and identify the most critical untested code paths. Suggest which to prioritize."
Automated Refactoring Suggestions
Not automated execution — but automated analysis that surfaces what needs attention:
claude -p "Identify files with high complexity, long functions, or repeated code patterns. Suggest specific refactoring targets."
Claude Code in Multi-Agent Pipelines
Headless mode becomes more powerful when Claude Code isn’t just running on a schedule, but acting as one node in a larger automated system.
Chaining Agents
You can chain Claude Code with other agents or services by passing output between them. For example:
- Claude Code analyzes a codebase and outputs a JSON report
- A Python script reads that JSON and sends it to a Slack webhook
- Another Claude invocation takes the Slack response and updates a tracking document
Each step is a discrete process. The -p flag makes Claude Code composable in the same way command-line tools are composable.
Triggering from Webhooks
If you’re running Claude Code on a server, you can trigger it from a webhook using a simple endpoint. GitHub Actions, for example, can trigger a shell command on a runner:
- name: Run Claude Code Analysis
env:
ANTHROPIC_API_KEY: $
run: |
claude -p "Review this PR for security issues and output a JSON summary" --output-format json > analysis.json
This puts Claude Code into your CI/CD pipeline without any custom infrastructure.
Passing Context to Headless Agents
One limitation of headless mode: your prompt is the only input. You can’t interactively clarify. So prompts need to be specific and complete.
Some patterns that help:
Include file content inline:
DIFF=$(git diff HEAD~1)
claude -p "Review this diff for issues: $DIFF"
Reference files by path:
claude -p "Read the file at ./src/auth.js and audit it for common authentication vulnerabilities"
Specify output format in the prompt:
claude -p "Analyze the test results in ./test-results.xml and return a JSON object with: total_tests, failed_tests, and a list of failing test names"
Being explicit about what you want back makes automated processing much more reliable.
Where MindStudio Fits Into This Picture
Claude Code headless mode is powerful, but it has a natural scope: it runs code tasks on files and directories. When your automated agents need to do more — send emails, update CRM records, post to Slack, trigger workflows in other tools, generate reports — you’re wiring together a lot of custom infrastructure.
That’s the gap MindStudio fills.
MindStudio is a platform for building and deploying autonomous background agents — the kind that run on a schedule, respond to triggers, and connect to your business tools without custom plumbing. It has built-in integrations with 1,000+ tools, including HubSpot, Salesforce, Slack, Google Workspace, Notion, and Airtable. You configure the logic visually, pick your trigger (a schedule, a webhook, an email), and the agent runs.
For developers already working with Claude Code, MindStudio’s Agent Skills Plugin is worth knowing about. It’s an npm SDK (@mindstudio-ai/agent) that lets any agent — including a Claude Code headless workflow — call MindStudio’s 120+ typed capabilities as simple method calls.
So instead of building custom code to send an email or post a Slack message after your Claude Code agent finishes, you do:
await agent.sendEmail({ to: "team@company.com", subject: "Code Review Complete", body: reviewResult });
await agent.postToSlack({ channel: "#engineering", message: reviewResult });
The plugin handles rate limiting, retries, and authentication. Your agent focuses on the reasoning, not the infrastructure.
If you want to run fully autonomous AI workflows without managing cron jobs or custom servers, MindStudio’s scheduled agent type handles that end-to-end — including access to Claude and 200+ other AI models with no separate API key required.
You can try MindStudio free at mindstudio.ai.
Common Problems and How to Fix Them
Even with a working setup, headless mode has some common failure points.
Claude Isn’t Found in Cron
Symptom: The cron job runs but fails with “command not found.”
Fix: Use the full path to the Claude binary. Find it with which claude in your terminal, then use that path in cron. Or add the npm bin directory to your PATH in the cron environment.
API Key Not Available
Symptom: Authentication errors when cron runs, but it works in your terminal.
Fix: Cron doesn’t load your shell profile. Set the API key explicitly in the cron command, or source a .env file that contains it. Never hardcode keys in the crontab itself if others have access to the system.
Agent Hangs Waiting for Input
Symptom: The cron job appears to run but never completes.
Fix: Claude Code is waiting for interactive input. Use --dangerously-skip-permissions if the task requires it, or redesign the prompt so it doesn’t trigger permission requests. You can also set a timeout using the timeout command:
timeout 300 claude -p "your prompt" || echo "Claude timed out" >> error.log
Output Too Large
Symptom: Tasks on large codebases produce truncated output or hit token limits.
Fix: Scope your prompts narrowly. Instead of “review the entire codebase,” try “review files changed in the last 7 days” or “review only the authentication module.” Large sweeping tasks are better broken into smaller targeted ones.
Prompt Needs Context That Isn’t in the Codebase
Symptom: Claude gives generic output that doesn’t account for project-specific context.
Fix: Include context in the prompt. Add a CLAUDE.md file at the project root — Claude Code reads this automatically and uses it as project context. Document conventions, important patterns, and anything Claude should know about your codebase there.
Frequently Asked Questions
What is Claude Code headless mode?
Claude Code headless mode is a way to run Claude Code non-interactively using the -p flag. Instead of opening an interactive session, you pass the prompt directly on the command line, and Claude executes the task and outputs the result to stdout. This makes it suitable for automation, scheduling, and use as part of larger pipelines.
How do I use the -p flag in Claude Code?
Add -p followed by your prompt in quotes when invoking Claude Code from the terminal:
claude -p "Your prompt here"
Claude will run the task without any interactive session and return the output. You can combine this with other flags like --output-format json or redirect output to a file.
Can I run Claude Code on a schedule automatically?
Yes. The most common method is using cron on Unix-based systems. You add an entry to your crontab that runs the Claude Code command at your chosen interval. Make sure to set environment variables (including ANTHROPIC_API_KEY) explicitly in the cron environment, since cron doesn’t load your shell profile.
Is headless mode safe to use with —dangerously-skip-permissions?
It depends on your setup. The --dangerously-skip-permissions flag removes interactive confirmation prompts, which is necessary for fully automated runs. But it also means Claude can execute actions without asking first. Use it only with well-tested prompts, in isolated environments (containers, CI runners, sandboxed repos), and when you fully understand what Claude will do. Start with read-only operations until you’re confident.
What’s the difference between Claude Code headless mode and the Claude API?
The Claude API lets you send messages to Claude programmatically and receive responses. Claude Code headless mode runs Claude with agentic capabilities — file access, shell execution, git operations — in a specific directory context. Headless mode is about running Claude as a local agent that can take actions in your codebase. The API is about building applications that send prompts and process completions.
Can Claude Code headless mode work in GitHub Actions or other CI systems?
Yes. You can run Claude Code as a step in a GitHub Actions workflow by installing it as an npm package and passing your API key as a secret. This lets you trigger Claude Code analysis on pull requests, after merges, or on any other GitHub event. The output can be posted as a PR comment, saved as an artifact, or used to gate merges.
Key Takeaways
- Claude Code headless mode uses the
-pflag to run tasks non-interactively, making it suitable for automation and scheduled workflows. - Cron is the simplest way to schedule Claude Code on Unix systems — but requires careful handling of environment variables and paths.
- The
--dangerously-skip-permissionsflag removes interactive confirmation prompts; use it only in controlled, well-tested environments. - Design headless prompts to be specific and self-contained — they need all context upfront since there’s no interactive follow-up.
- Claude Code works best as one node in a larger automated pipeline when combined with tools that handle notifications, integrations, and business logic.
- Platforms like MindStudio handle the infrastructure layer for scheduled agents and tool integrations, so you can focus on what the agent actually does rather than how it runs.
If you’re looking to build autonomous agents that go beyond the terminal — connecting to business tools, running on schedules, and handling the plumbing automatically — MindStudio is worth exploring. It’s free to start, and the average agent takes less than an hour to build.