# Running Claude Code in Headless or CI Mode: The Complete Print Mode Guide

> Master running Claude Code in headless or CI mode using the Print mode with the claude -p command. Execute prompts non-interactively for automation and CI/CD pipelines.

- Repository: [Luong NGUYEN/claude-howto](https://github.com/luongnv89/claude-howto)
- Tags: how-to-guide
- Published: 2026-03-30

---

**Run Claude Code non-interactively using `claude -p` (Print mode) to execute single prompts in automation scripts and CI/CD pipelines without launching the interactive REPL.**

According to the `luongnv89/claude-howto` repository, Print mode replaces the deprecated `--headless` flag and provides a robust, machine-friendly interface for automated workflows. This architecture streams responses directly to stdout and exits with a return code, enabling seamless integration with GitHub Actions, shell scripts, and other DevOps tooling.

## Understanding Print Mode Architecture

Print mode (`-p`) fundamentally changes how the Claude CLI processes input by bypassing the interactive terminal UI. As documented in [`09-advanced-features/README.md`](https://github.com/luongnv89/claude-howto/blob/main/09-advanced-features/README.md) (lines 39-42), this mode sends a single prompt to the Claude API, streams the response back to the caller, and terminates immediately upon completion.

### Core Components

- **CLI front-end** (`claude`): Parses command-line flags and routes execution to either the interactive REPL or Print mode based on the presence of the `-p` flag.
- **Print mode processor**: Handles single-query execution, disables terminal UI rendering, and manages output formatting.
- **Permission system**: In headless environments, `--permission-mode dontAsk` (or `--enable-auto-mode`) suppresses interactive tool-execution prompts that would otherwise stall automation.
- **Session handler**: By default, Claude persists session state to disk, but `--no-session-persistence` creates stateless runs ideal for CI containers.

## Migrating from the Legacy --headless Flag

The repository's [`CHANGELOG.md`](https://github.com/luongnv89/claude-howto/blob/main/CHANGELOG.md) (lines 99-101) documents the migration path for users of the older syntax:

> "Fix CLI syntax: replace `claude-code --headless` with `claude -p` (print mode)"

This change consolidates headless functionality under the standard `claude` binary using the `-p` (or `--print`) flag. The [`10-cli/README.md`](https://github.com/luongnv89/claude-howto/blob/main/10-cli/README.md) file (lines 31-34) confirms the current syntax: `claude -p "query"` executes in Print mode, queries the API, then exits.

## Essential Flags for Non-Interactive Execution

When running Claude Code in headless or CI mode, these flags ensure reliable, unattended operation:

- **`--permission-mode dontAsk`**: Disables all permission prompts. Tools execute without user confirmation, preventing job timeouts.
- **`--enable-auto-mode`**: Alternative to `dontAsk` that enables automatic tool execution with implicit permissions.
- **`--no-session-persistence`**: Prevents writing session files to disk, keeping CI runs stateless and avoiding file system conflicts in ephemeral containers.
- **`--output-format json`**: Returns structured JSON instead of markdown text, enabling downstream parsing with `jq` or GitHub Actions scripts.
- **`--max-turns N`**: Limits autonomous Claude iterations to prevent excessive API usage and control execution time.

## Implementing Claude Code in GitHub Actions

The repository provides a complete CI/CD integration pattern. Below is a production-ready GitHub Actions workflow derived from the source documentation that runs automated code reviews using Claude's headless mode:

```yaml

# .github/workflows/code-review.yml

name: AI Code Review

on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Claude Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p --output-format json \
            --permission-mode dontAsk \
            --max-turns 3 \
            "Review this PR for:
             - Code quality issues
             - Security vulnerabilities
             - Performance concerns
             - Test coverage
             Output results as JSON" > review.json

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: JSON.stringify(review, null, 2)
            });

```

Key implementation details in this workflow:

- `claude -p` launches Print mode for non-interactive execution.
- `--output-format json` produces machine-readable output consumed by the `github-script` step.
- `--permission-mode dontAsk` guarantees the job completes without hanging on permission prompts.
- `--max-turns 3` constrains the Claude agent to three reasoning iterations, optimizing for CI billing and speed.

The existing [`.github/workflows/ci.yml`](https://github.com/luongnv89/claude-howto/blob/main/.github/workflows/ci.yml) (lines 14-31) demonstrates how such Claude steps integrate alongside standard Python testing matrices and security scanning jobs.

## Command Reference for Automation

| Goal | Command |
|------|---------|
| Run single task locally | `claude -p "Run all tests"` |
| Pipe file content to Claude | `cat error.log \| claude -p "Explain these errors"` |
| Structured CI output | `claude -p --output-format json --permission-mode dontAsk "Analyze code quality"` |
| Stateless execution | `claude -p --no-session-persistence "One-off analysis"` |
| Auto-execute permissions | `claude -p --enable-auto-mode "Refactor this module"` |
| Limit iterations | `claude -p --max-turns 5 "Complex task"` |

These patterns are catalogued in [`QUICK_REFERENCE.md`](https://github.com/luongnv89/claude-howto/blob/main/QUICK_REFERENCE.md) (lines 25-34) under the CI/CD Integration section.

## Processing Piped Input in Shell Scripts

Print mode accepts piped stdin, enabling powerful shell pipelines:

```bash

# Analyze log files

cat system.log | claude -p "Extract error patterns and summarize frequencies"

# Code generation from templates

cat template.py | claude -p "Customize this template for Django 4.2"

# Filter urgent items

claude -p "List TODO comments" | grep -i urgent

```

## Summary

- **Print mode** (`claude -p`) is the current standard for running Claude Code in headless or CI mode, replacing the deprecated `--headless` flag as noted in [`CHANGELOG.md`](https://github.com/luongnv89/claude-howto/blob/main/CHANGELOG.md).
- **Non-interactive execution** requires explicit permission handling via `--permission-mode dontAsk` or `--enable-auto-mode` to prevent automation stalls.
- **Machine-readable output** is achieved through `--output-format json`, enabling integration with GitHub Actions, Jenkins, and other CI platforms.
- **Stateless operation** using `--no-session-persistence` ensures ephemeral CI containers exit cleanly without leaving session artifacts.
- **Cost and safety controls** like `--max-turns` limit API consumption during automated runs.

## Frequently Asked Questions

### What happened to the --headless flag in Claude Code?

The `--headless` flag was deprecated and replaced by Print mode (`-p` or `--print`). According to [`CHANGELOG.md`](https://github.com/luongnv89/claude-howto/blob/main/CHANGELOG.md) (lines 99-101), you should migrate all automation scripts from `claude-code --headless` to `claude -p` to ensure compatibility with current versions.

### How do I prevent Claude Code from hanging in CI pipelines?

Use `--permission-mode dontAsk` to disable interactive permission prompts, or `--enable-auto-mode` to allow automatic tool execution. Without these flags, Claude may pause indefinitely waiting for user input when attempting to read files or execute commands.

### Can I use Claude Code in headless mode without saving session files?

Yes. Append `--no-session-persistence` to your `claude -p` command. This prevents the creation of session files on disk, making it safe for ephemeral CI environments where file system state does not persist between job runs.

### What output format should I use for parsing Claude Code results in automation?

Use `--output-format json` (or `stream-json` for streaming JSON). This returns structured data that shell scripts, GitHub Actions workflows, and other automation tools can parse reliably, rather than markdown-formatted text intended for human reading.