Skip to main content

Overview

Exec mode allows you to run Codex non-interactively for automation, CI/CD pipelines, and scripted workflows. Instead of launching the interactive TUI, Codex executes your prompt, completes the task, and exits automatically.
Exec mode is ideal for automated workflows where you need Codex to complete a task without human intervention.

Basic Usage

The codex exec command runs Codex in non-interactive mode:
codex exec "your prompt here"
You can also pass the prompt via stdin:
echo "update the changelog" | codex exec
Or from a file:
codex exec < task.txt

Command-Line Options

--ephemeral
boolean
default:"false"
Run without persisting session rollout files to disk. Useful for temporary automation tasks.
--json
boolean
default:"false"
Print events to stdout as JSONL for programmatic parsing.
--output-last-message
string
Write the last message from the agent to the specified file.
codex exec -o response.md "explain the architecture"
--output-schema
string
Path to a JSON Schema file describing the model’s final response shape.
--color
string
default:"auto"
Control color output: always, never, or auto.
--progress-cursor
boolean
default:"false"
Force cursor-based progress updates in exec mode.

CI/CD Integration

GitHub Actions Example

name: Update Changelog

on:
  push:
    branches: [main]

jobs:
  changelog:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Codex
        run: npm install -g @openai/codex
      
      - name: Update changelog via Codex
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          codex exec --sandbox workspace-write \
            "update CHANGELOG.md for the latest release"
      
      - name: Commit changes
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add CHANGELOG.md
          git commit -m "docs: update changelog [skip ci]"
          git push

Environment Variables

Always store API keys and sensitive credentials as secrets in your CI/CD platform.
# Required: OpenAI API key
export OPENAI_API_KEY="sk-..."

# Optional: Suppress interactive UI prompts
export CODEX_QUIET_MODE=1

# Optional: Enable verbose logging (see Tracing guide)
export RUST_LOG=info

Approval Modes for Automation

1

Full Auto Mode

Use --full-auto for complete automation with sandboxing:
codex exec --full-auto "fix all linting errors"
This is equivalent to:
codex exec --sandbox workspace-write "fix all linting errors"
2

Danger Mode (Use with Caution)

Only for externally sandboxed environments:
codex exec --dangerously-bypass-approvals-and-sandbox "run tests"
This disables all safety checks. Only use inside Docker or other isolated environments.

Output Formats

Human-Readable Output

By default, exec mode prints human-readable progress to stderr:
codex exec "summarize the project"
Output:
⚙ Reading project files...
✓ Analysis complete
📝 Writing summary...

[Summary content appears here]

JSON Lines (JSONL) Output

For programmatic parsing, use --json:
codex exec --json "list all API endpoints" > results.jsonl
Each line is a JSON event:
{"type":"AgentMessage","content":"Analyzing API routes..."}
{"type":"FileChange","path":"api_summary.md","status":"created"}
{"type":"TurnComplete","success":true}

Structured Output with Schema

Provide a JSON Schema to enforce structured output:
codex exec \
  --output-schema schema.json \
  --output-last-message result.json \
  "extract all dependencies"
schema.json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "dependencies": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "version": {"type": "string"},
          "type": {"enum": ["runtime", "dev", "peer"]}
        },
        "required": ["name", "version", "type"]
      }
    }
  },
  "required": ["dependencies"]
}

Working with Images

Attach images to your exec prompt:
# Single image
codex exec --image screenshot.png "implement this design"

# Multiple images
codex exec --image design1.png,design2.png "compare these mockups"

Session Management

Ephemeral Sessions

Use --ephemeral to avoid writing session data to disk:
codex exec --ephemeral "quick analysis task"
Benefits:
  • Faster startup (no session loading)
  • No disk I/O overhead
  • Clean environment for one-off tasks

Resume Previous Sessions

You can resume a previous exec session:
# Resume the most recent session
codex exec resume --last

# Resume by session ID
codex exec resume <session-id>

# Resume with additional prompt
codex exec resume --last "continue with unit tests"

Error Handling

Exec mode exits with status codes for automation:
Exit Code 0
success
Task completed successfully
Exit Code 1
error
Task failed or error occurred
Example with error handling:
#!/bin/bash
set -e

if codex exec --ephemeral "run tests and report failures"; then
  echo "Tests passed!"
  notify-send "Codex: Tests passed"
else
  echo "Tests failed. Check logs."
  exit 1
fi

Best Practices

Use Ephemeral Mode

For CI/CD tasks that don’t need session persistence

Capture Output

Use --output-last-message to save results

Enable JSON Mode

Parse events programmatically with --json

Set Appropriate Sandbox

Use --full-auto for safe automation

Examples

codex exec \
  --sandbox workspace-write \
  --output-last-message docs/api.md \
  "generate comprehensive API documentation from source code"
# Review uncommitted changes
codex exec review --uncommitted

# Review against base branch
codex exec review --base main

# Review specific commit
codex exec review --commit abc123 --title "feat: add new feature"
#!/bin/bash
for file in src/*.js; do
  codex exec --ephemeral "add JSDoc comments to $file"
done
# Cron job: daily dependency updates
0 2 * * * cd /path/to/project && \
  codex exec --full-auto "update dependencies and run tests" \
  >> /var/log/codex-maintenance.log 2>&1

Troubleshooting

Ensure you’re using an appropriate approval mode:
  • Use --full-auto for automated execution
  • Check that your prompt is clear and has defined completion criteria
  • Enable verbose logging to see what’s happening: RUST_LOG=debug codex exec ...
  • Set explicit timeouts in your CI configuration
  • Use --ephemeral to reduce startup overhead
  • Consider breaking large tasks into smaller steps
  • Verify OPENAI_API_KEY is set correctly
  • Check that the API key has sufficient permissions
  • Ensure your organization allows API access

See Also

Execution Policies

Control which commands can be executed

Tracing & Logging

Debug with verbose logging

Custom Instructions

Add project-specific guidance

Sandbox Configuration

Configure sandboxing behavior