Codex exec: Run Codex Headless in Scripts and Cron

codex exec is the command that runs OpenAI's Codex CLI without anyone at the keyboard: one prompt in, the agent works, one answer out, an exit code. It is what you put in a shell script, a GitHub Actions job or a crontab. The official page covers the basics, but not the exit codes, not what happens when the sandbox refuses an action, and not how to tell a run that did its job from one that only said it tried. We ran 30 codex exec invocations on 2026-11-10 with codex-cli 0.166.0 (npm had 0.167.0 by the end of the day) to find out, and every command and output below comes from those runs.

The surprise first: asked to write a file in the default read-only sandbox, Codex failed the write, said so, and exited with code 0. A job that checks only $? reports success for a run that did nothing.

codex exec at a glance

I want to... Flag or form
Run a prompt codex exec "prompt" (alias codex e)
Read the prompt from stdin or a file codex exec - < prompt.txt
Add piped context to a prompt cat ci.log | codex exec "Summarize this log" (appended as a <stdin> block)
Get machine-readable events --json (JSONL on stdout)
Get the final answer in a file -o last.txt (--output-last-message)
Force the shape of the answer --output-schema schema.json
Let it write in the repository --sandbox workspace-write
Let it do anything --dangerously-bypass-approvals-and-sandbox (containers and VMs only)
Run outside a git repository --skip-git-repo-check
Work in another directory -C <dir> (--cd), --add-dir <dir> for extra writable folders
Pick the model and effort -m gpt-6.1-sol -c model_reasoning_effort=high
Continue a session codex exec resume <id> "prompt", codex exec resume --last
Not keep the session on disk --ephemeral
Ignore my config.toml --ignore-user-config (auth still comes from CODEX_HOME)
Review changes codex exec review --uncommitted, --base main, --commit <sha>

The full list is in codex exec --help. Flags we don't cover: -i (attach images), --oss and --local-provider (LM Studio or Ollama), --color, --dangerously-bypass-hook-trust.

Your first codex exec run

Prompt as argument, from stdin, or both

There are three ways in, and they behave differently:

codex exec "Answer with the single word hi."     # prompt as argument
codex exec - < prompt.txt                         # the whole prompt from stdin
cat ci.log | codex exec "Summarize the piped log in one line."   # prompt + piped context

The third form is the useful one in pipelines. With a two-line npm error log piped in, Codex answered npm failed to resolve dependencies because react-dom@18.3.1 requires React ^18. The - form reads only the prompt: our prompt.txt said "Summarize the piped log in one line." and nothing else, so Codex answered "Please paste the piped log so I can summarize it in one line." To send instructions and data from files, concatenate them: cat prompt.txt ci.log | codex exec -.

stdout vs stderr: what goes where

Without --json, stdout gets only the agent's final message. Everything else goes to stderr: a header with the settings actually used, the transcript, warnings, and a tokens used line at the end. Here is the stderr header of a run with --ignore-user-config:

OpenAI Codex v0.166.0
--------
workdir: /tmp/cxt/repo
model: gpt-6.1-sol
provider: openai
approval: never
sandbox: read-only
reasoning effort: none
reasoning summaries: none
session id: 01a1c4b3-f2f6-7b13-b438-26f9cc56edbc
--------

Two things to note. That header is the quickest way to check what a scripted run really used (model, sandbox, effort). And with no config, the default reasoning effort in exec was none. The split also means codex exec "..." | tee answer.txt captures the answer cleanly while the progress stays on your terminal or in 2> run.log.

Every run with a prompt argument also printed Reading additional input from stdin... on stderr, even with stdin redirected from /dev/null. With /dev/null it is harmless. With a pipe that never closes, it is not: see Troubleshooting below.

"Not inside a trusted directory"

In a folder that is not a git repository:

$ codex exec "say hi"; echo "exit=$?"
Not inside a trusted directory and --skip-git-repo-check was not specified.
exit=1

The message talks about trust, but the check is about git. Our config.toml marks /tmp as trusted, and a run in a non-git folder under /tmp was still refused with the same message. --skip-git-repo-check lets it run. The guard exists because git is your undo button: in a repository, git diff shows what the run did and git checkout . reverts it. Outside one, nothing does.

Two related flags: -C <dir> sets the working root without a cd, and --add-dir <dir> adds a folder the agent may also write to under workspace-write.

Permissions without anyone to answer

The three sandbox modes, read-only by default

codex exec never asks for approval (the header says approval: never). What limits it is the sandbox, chosen with -s / --sandbox:

Mode Writes What we saw (0.166.0)
read-only (default) None uname -s > os.txt failed with Read-only file system, exit code 0
workspace-write The working directory, /tmp, $TMPDIR (from the header: sandbox: workspace-write [workdir, /tmp, $TMPDIR]) The same command wrote os.txt; a write to /root/cxt-probe.txt was refused, exit code 0
danger-full-access Anywhere your user can write Not run on our machine, by design

Note the /tmp in workspace-write: a job that must not touch shared temporary files needs a container, not just this mode. On Linux, Codex warned that bubblewrap was not on PATH and used its bundled copy; installing bubblewrap from your distribution removes the warning.

--full-auto is gone: what to use instead

Most guides still show codex exec --full-auto. On 0.166.0:

$ codex exec --full-auto "x"; echo "exit=$?"
error: unexpected argument '--full-auto' found

  tip: to pass '--full-auto' as a value, use '-- --full-auto'
exit=2

-a never (--ask-for-approval) is rejected the same way, exit code 2. What replaces them:

The cross-CLI view, with the equivalent flags for Claude Code, Gemini, Antigravity and Copilot, is in our dangerously-skip-permissions guide.

--dangerously-bypass-approvals-and-sandbox (yolo)

This flag turns off both the approvals and the sandbox. The help calls it "EXTREMELY DANGEROUS. Intended solely for running in environments that are externally sandboxed", and that is the rule: a disposable container or VM, no home directory mounted, no personal credentials, a fresh clone. It is what we use for benchmarks, inside a box: our Codex vs Claude Code benchmark ran codex exec --json --dangerously-bypass-approvals-and-sandbox --ignore-user-config --skip-git-repo-check -C "$WORKTREE".

Machine-readable output

--json: the event stream

--json replaces the human output with one JSON object per line on stdout. Here is the full stream of our read-only test, a prompt asking Codex to run uname -s, write it to os.txt and report (lines shortened):

{"type":"thread.started","thread_id":"01a1c4b3-91c0-7ad1-8aba-00637fceab10"}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"I’ll run `uname -s` and try to write its output to `os.txt`, then verify the file."}}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc 'uname -s > os.txt'","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc 'uname -s > os.txt'","aggregated_output":"/bin/bash: line 1: os.txt: Read-only file system\n","exit_code":1,"status":"failed"}}
{"type":"item.started","item":{"id":"item_2","type":"command_execution","command":"/bin/bash -lc 'if [ -f os.txt ]; then cat os.txt; else uname -s; fi'","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_2","type":"command_execution","aggregated_output":"Linux\n","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"{\"status\":\"failed\",\"os\":\"Linux\",\"reason\":\"Could not create os.txt because the filesystem is read-only.\"}"}}
{"type":"turn.completed","usage":{"input_tokens":36572,"cached_input_tokens":18048,"cache_write_input_tokens":0,"output_tokens":131,"reasoning_output_tokens":0}}

The event types you will meet: thread.started (the session id), turn.started, item.started / item.completed (items of type agent_message, command_execution with its exit_code and status, error), turn.completed with usage, and on failure error events followed by turn.failed. To list the commands that failed:

jq -c 'select(.type=="item.completed" and .item.status=="failed") | .item.command' events.jsonl

-o, --output-last-message

-o last.txt writes the final agent message to a file, whatever goes to stdout. With --json this is the simplest way to get the answer without parsing the stream: the events go to one file, the answer to another.

--output-schema: force the shape of the answer

Our schema for the test above:

{
  "type": "object",
  "properties": {
    "status": { "type": "string", "enum": ["done", "failed"] },
    "os": { "type": "string" },
    "reason": { "type": "string" }
  },
  "required": ["status", "os", "reason"],
  "additionalProperties": false
}
codex exec --json --sandbox read-only --ephemeral \
  --output-schema schema.json -o last.json \
  "Run uname -s, write its output to os.txt, then answer. status is done only if os.txt exists with the output." \
  < /dev/null > events.jsonl

last.json contained exactly {"status":"failed","os":"Linux","reason":"Could not create os.txt because the filesystem is read-only."}. That status field is the whole point: the exit code was 0, the schema said failed. A schema is the cheapest way to make the model state its own outcome in a form jq -e can test.

Reading token usage, and what a run costs

Each turn.completed carries usage. Summed over a run, with the GPT-6.1 Sol API list prices we used in our October benchmark ($2 per million input tokens, $0.10 cached, $10 output):

jq -s '[.[] | select(.type=="turn.completed") | .usage]
  | {input: (map(.input_tokens)|add), cached: (map(.cached_input_tokens)|add), output: (map(.output_tokens)|add)}
  | . + {usd: (((.input - .cached) * 2 + .cached * 0.10 + .output * 10) / 1e6)}' events.jsonl

For the read-only test: 36,572 input tokens (18,048 cached), 131 output, $0.040. Two numbers from our runs worth knowing before you schedule anything:

On a ChatGPT plan you don't pay these amounts, but the same tokens count against your usage limits.

Exit codes, and why 0 is not "done"

Situation (codex-cli 0.166.0) Exit code Time
Turn completed, task done 0 4 to 10 s for small prompts
Turn completed, write refused by the sandbox 0 9.9 s
Not a git repository, no --skip-git-repo-check 1 1.4 s
Invalid CODEX_API_KEY (401 invalid_api_key) 1 15.5 s, after 10 retries
No credentials at all in CODEX_HOME 1 15.9 s
Unknown model (-m no-such-model on a ChatGPT account) 1 3.3 s
A required = true MCP server fails to start 1 2.2 s
--worktree with --ephemeral or --ignore-user-config 1 instant
Resume of an --ephemeral session 1 0.8 s
Unknown flag (--full-auto, -a) 2 instant
Killed by timeout 124 your limit
node not on PATH (cron) 127 instant

So a non-zero code means Codex could not run. Zero means the turn ended, not that the work happened. We found the same pattern in other CLIs: Claude Code in -p mode also exits 0 when it is denied a tool call (Claude Code vs GitHub Copilot has more). An open Codex issue, #37717, reports codex exec exiting 0 after generating two of six requested images, with none saved at the requested paths.

How to judge a run instead:

  1. Check the artifact. If the job must write REPORT.md, test [ -s REPORT.md ]. Nothing else is as reliable.
  2. Make the model state its outcome with --output-schema and a status field, then jq -e '.status == "done"' last.json.
  3. Read failed items as a signal, not a verdict. In our cron test below, the task succeeded and the stream still had one failed command: an rg search that found no match and exited 1. Log them; don't fail the job on them alone.

Resuming and forking sessions

The session id is the thread_id of thread.started (or the session id: line on stderr). We started a session with "Remember the code word PELICAN. Answer only: ok.", then:

codex exec resume --last --json "What is the code word? Answer with it only."      # PELICAN
codex exec resume --json 01a1c4b4-9c81-7012-ba3d-421a420031ac "Repeat the code word in lowercase only."   # pelican
codex exec fork --json 01a1c4b4-9c81-7012-ba3d-421a420031ac "Spell the code word backwards, only that."  # NACILEP

Both resumes kept the same thread_id; the fork got a new one (01a1c4b5-92f4-...) with the history up to that point. --last picks the most recent session started in the current directory (--all lifts that filter), which matters on a machine where several jobs run Codex. resume also accepts a thread name instead of a UUID.

Two limits: a run made with --ephemeral cannot be resumed (no rollout found for thread id ..., exit 1), and exec resume has no --sandbox flag, so pass the mode as -c sandbox_mode=workspace-write.

Models, reasoning effort and config overrides

--worktree runs the session in a new git worktree managed by Codex. Ours was created at ~/.codex/worktrees/d654/repo3, in detached HEAD, and was still there after the run: the file Codex wrote lives in that worktree, not in your checkout, and you clean it up with git worktree remove. It refuses --ephemeral and --ignore-user-config.

Authentication in CI and on a server

codex exec in GitHub Actions

A minimal read-only review job, with the version pinned and the result judged on the schema, not the exit code. OpenAI also publishes openai/codex-action; a plain step keeps every flag visible.

name: codex-review
on:
  pull_request:
jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm install -g @openai/codex@0.166.0
      - name: Review with codex exec
        env:
          CODEX_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          codex exec --json --sandbox read-only --ephemeral \
            --output-schema .github/codex/review.schema.json -o review.json \
            "Review the changes of this branch against origin/${{ github.base_ref }} for bugs. \
          Set status to done once every changed file is reviewed." \
            < /dev/null > events.jsonl
          jq -e '.status == "done"' review.json
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: codex-run
          path: |
            events.jsonl
            review.json

What matters: the pinned version (flags change between releases, --full-auto did), timeout-minutes as the outer limit, < /dev/null, and the events uploaded even on failure so you can read what happened. Our CI failure to pull request template is the write-side version of this pattern. Claude Code in GitHub Actions deserves its own article; we won't compare them here.

codex exec in a cron job

This is the script we ran once by hand on our test repository. It takes a lock so two runs never overlap, bounds the run with timeout, keeps the events and the answer per run, and decides on the artifact:

#!/usr/bin/env bash
# Nightly codex exec job: one run at a time, bounded in time, judged on its artifact.
set -euo pipefail

export PATH="$HOME/.nvm/versions/node/v24.21.0/bin:/usr/local/bin:/usr/bin:/bin"
REPO="${REPO:-/srv/myapp}"
LOGS="${LOGS:-$HOME/codex-logs}"
SCHEMA="${SCHEMA:-$HOME/bin/report.schema.json}"
STAMP="$(date -u +%Y-%m-%dT%H%M%SZ)"
REPORT="reports/$(date -u +%F).md"
mkdir -p "$LOGS"

exec 9>"/tmp/codex-nightly.lock"
flock -n 9 || { echo "$STAMP previous run still going, skipped" >> "$LOGS/cron.log"; exit 0; }

cd "$REPO"
code=0
timeout 900 codex exec --json --sandbox workspace-write --ephemeral \
  --output-schema "$SCHEMA" -o "$LOGS/$STAMP.last.json" \
  "Summarize the commits of the last 24 hours (git log --since=24.hours) in $REPORT, \
creating the folder if needed. Set status to done only if the file exists." \
  < /dev/null > "$LOGS/$STAMP.jsonl" 2> "$LOGS/$STAMP.err" || code=$?

failed=$(jq -s '[.[] | select(.type=="item.completed" and .item.status=="failed")] | length' "$LOGS/$STAMP.jsonl")
status=$(jq -r '.status // "missing"' "$LOGS/$STAMP.last.json" 2>/dev/null || echo missing)
echo "$STAMP exit=$code status=$status failed_items=$failed" >> "$LOGS/cron.log"

[ "$code" -eq 0 ] && [ "$status" = done ] && [ -s "$REPORT" ] || exit 1

The schema is the status / summary variant of the one above. Our run logged exit=0 status=done failed_items=1 (the harmless rg with no match), wrote a correct two-commit summary, and cost about $0.055 at API prices (80,257 input tokens, 59,392 cached, 757 output). The crontab line:

30 4 * * 1-5  /home/dev/bin/codex-nightly.sh

The export PATH line is not decoration. Codex installed with npm is a Node script (#!/usr/bin/env node), and cron's minimal PATH has no Node from nvm: the same codex --version with PATH=/usr/bin:/bin failed with /usr/bin/env: 'node': No such file or directory, exit 127. Scheduled Codex jobs in general (retries, missed runs, notifications) will get their own article. If you would rather not run them on your own machine at all, our Cursor background agents post weighs cloud agents against a CLI you host. Typical jobs for this script: a nightly issue triage or weekly dependency updates.

Running codex exec on a schedule on your own machine

This is what SideHub does for its users: an automation or a workflow step set to Codex types codex exec --skip-git-repo-check in a terminal on your own machine, through an agent you install there. Read-only steps add --sandbox read-only -c approval_policy=never, steps under a tool policy --sandbox workspace-write -c approval_policy=never, the others --dangerously-bypass-approvals-and-sandbox; a resumed step uses codex exec resume, with the sandbox passed through -c sandbox_mode=... because resume has no --sandbox. Each run keeps its exit code, the last lines of its output and the token usage read from Codex's session file, and a run stopped by the plan's usage limit ends as such, with the reset time when Codex gives it, instead of a bare failure. A run that changed the repository lands in To review with its diff, and nothing is pushed until a person confirms. The Codex codes, Claude reviews template chains the two CLIs that way.

codex exec review

codex exec review runs Codex's built-in code review, headless and read-only. It takes --uncommitted (staged, unstaged and untracked changes), --base <branch> or --commit <sha>, plus an optional prompt with extra instructions. We planted a bug in an uncommitted change (return sum(values) / len(values) + 1) and ran codex exec review --uncommitted. Codex returned one finding, priority [P2], titled "Remove the extra increment from the average", pointing at calc.py:5-5:

For any nonempty numeric sequence, adding 1 makes the result one greater than the arithmetic mean.
For example, `average([2, 4])` returns `4.0` instead of `3.0`.

It took 18.2 seconds and exited 0; --json, -o and --output-schema work here too. Our daily PR review template runs this kind of review every morning.

codex exec vs claude -p

codex exec (0.166.0) claude -p (2.1.322)
Headless form codex exec "prompt" claude -p "prompt"
Machine-readable output --json (JSONL events) --output-format json or stream-json
Forced answer shape --output-schema <file> --json-schema <schema>
Unattended permissions Sandbox modes, approvals always off; --dangerously-bypass-approvals-and-sandbox Permission modes; --dangerously-skip-permissions
Resume codex exec resume <id> / --last, fork --resume <id>, --continue
Don't persist the session --ephemeral --no-session-persistence
Spending caps None in exec: use timeout --max-turns, --max-budget-usd
A refused action Exit 0 Exit 0

Both need the same discipline: judge on artifacts, cap time, isolate the permissionless mode. What each costs per task, measured on the same four tasks, is in our Codex vs Claude Code benchmark; the headless forms of Gemini CLI and Antigravity CLI are in Gemini CLI vs Claude Code.

Troubleshooting

How we tested

All runs on 2026-11-10, codex-cli 0.166.0 installed with npm, signed in with a ChatGPT account, on a Linux VPS (x86_64). Each run used a throwaway git repository under /tmp with two files (README.md, calc.py), and the real binary called through env -i HOME="$HOME" PATH=... so no environment variable of ours leaked in:

env -i HOME="$HOME" PATH="$NODE_BIN:/usr/bin:/bin" \
  codex exec --json --ignore-user-config --ephemeral --sandbox read-only "$PROMPT" \
  < /dev/null > run.out 2> run.err; echo "exit=$?"

Most runs used --ignore-user-config and --ephemeral, so the default model (gpt-6.1-sol) and no saved session; the resume and fork tests kept their session, and the --worktree test ran with our config (it refuses --ignore-user-config). The API key tests used a fresh, empty CODEX_HOME. 30 invocations in total, one run per case: these tests check how the CLI behaves, not how often a model succeeds. Nothing ran with danger-full-access or the bypass flag on this machine.

The verdict

codex exec is a solid building block for scripts and scheduled jobs, as long as you treat it like any other process that can fail quietly. Pin the version (0.166.0 here, and --full-auto already broke older scripts), redirect stdin from /dev/null, wrap it in timeout, pick the smallest sandbox that does the job, and judge each run on what it produced, with an --output-schema status as a second check. The exit code tells you whether Codex ran, not whether it did the work.