GuidesHosting choices

codex exec: Codex CLI's non-interactive mode, flags and CI

codex exec in Codex 0.172: prompt and stdin, --json events, -o, --output-schema, the sandbox default, resume, exit codes, CODEX_API_KEY and cron on a server.

November 27, 2026The Everpod team
The short answer

codex exec "your prompt" runs Codex CLI once with no interface and exits: progress goes to stderr, only the final message goes to stdout. It never stops to ask for approval. OpenAI’s docs say it runs in a read-only sandbox by default, but in Codex 0.172.0 (November 2026) the default can be workspace-write in a project with a trust decision, so in a script always pass --sandbox: read-only to look, workspace-write to let it edit files. Add --json for a stream of JSON events, -o file to save the last message, and --output-schema schema.json for a structured answer. It needs a Git repository unless you pass --skip-git-repo-check. --full-auto is gone. It signs in with your saved login, or with CODEX_API_KEY for one run.

The basic shape

codex exec "summarize the repository structure"   # prompt as an argument
cat prompt.txt | codex exec -                       # the whole prompt from stdin
git diff | codex exec "review this diff"            # argument is the task, stdin is context
Copied

The prompt comes from the argument, or from stdin when there is no argument or the argument is -. When you give both, the argument is the instruction and the piped text is appended as a <stdin> block. With no argument and nothing piped, it stops with:

No prompt provided. Either specify one as an argument or pipe the prompt into stdin.
Copied

In the default output mode the source treats stdout as sacred: only the final message is written there, and progress and warnings go to stderr. So codex exec "..." > answer.txt captures the answer alone, and 2>run.log keeps the trail.

Defaults: the sandbox, approvals, Git

Three defaults catch people who come from the interactive codex:

Project configuration and project-defined MCP servers load only in a trusted project, and --trust saves that trust; the untrusted project-local configuration guide covers what it saves and when not to use it. How the three sandbox modes and the approval policies differ is in the Codex sandbox guide.

--full-auto is gone

Older scripts and posts use codex exec --full-auto. The 0.172.0 source defines no such flag, and the docs say plainly: “--full-auto is no longer supported.” Replace it with one of these:

FlagWhat it does
--sandbox workspace-write
Edits allowed in the working directory, approvals still never asked. The usual replacement.
--approve-for-me
Routes approval requests through automatic review, with the workspace-write sandbox. Cannot be combined with --sandbox.
--dangerously-bypass-approvals-and-sandbox (--yolo)
No sandbox at all. The help text: “Intended solely for running in environments that are externally sandboxed.”

Every flag in 0.172.0

From codex-rs/exec/src/cli.rs and the shared options it wraps, at tag rust-v0.172.0:

FlagEffect
-m, --model
The model for this run
-s, --sandbox
read-only, workspace-write or danger-full-access
-C, --cd DIR
Use DIR as the working root
--add-dir DIR
Another directory writable beside the workspace
--skip-git-repo-check
Run outside a Git repository
--json
Events to stdout as JSON Lines
-o, --output-last-message FILE
Write the final message to FILE
--output-schema FILE
JSON Schema the final response must match
--ephemeral
Do not write session files to disk
-p, --profile NAME
Layer $CODEX_HOME/NAME.config.toml over your config
-c key=value
Override one config value
-i, --image FILE
Attach images to the prompt
--worktree
Run in a new managed Git worktree
--trust
Save trust for this project
--ignore-user-config
Skip $CODEX_HOME/config.toml (sign-in still read from there)
--ignore-rules
Skip user and project .rules files
--strict-config
Unknown config.toml fields become an error
--color
always, never or auto (default)
--oss, --local-provider
Use a local model provider (LM Studio or Ollama)
--approve-for-me, --yolo
See the table above

--trust and --ignore-user-config cannot be used together. For what -c and profiles can set, see Codex config.toml.

--json: the event stream

With --json, stdout becomes one JSON object per line. This is the sample from OpenAI’s docs (two lines wrapped here for width):

{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message",
 "text":"Repo contains docs, sdk, and examples directories."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,
 "output_tokens":122,"reasoning_output_tokens":0}}
Copied

The event types are thread.started, turn.started, turn.completed, turn.failed, error and the item.* events, whose items are agent messages, reasoning, command executions, file changes, MCP tool calls, web searches and plan updates. Two lines of jq cover the common needs:

# the final answer
codex exec --json "triage the failing test" | jq -r 'select(.type=="item.completed" and .item.type=="agent_message") | .item.text'

# the token usage of the run
codex exec --json "triage the failing test" | jq -c 'select(.type=="turn.completed") | .usage'
Copied

-o and --output-schema

-o path writes the final message to a file and, per the docs, “still prints it to stdout”, so a script can keep stdout for display and read the answer from the file.

--output-schema makes the final message conform to a JSON Schema. The docs’ example:

cat > schema.json <<'EOF'
{
  "type": "object",
  "properties": {
    "project_name": { "type": "string" },
    "programming_languages": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["project_name", "programming_languages"],
  "additionalProperties": false
}
EOF
codex exec "Extract project metadata" --output-schema ./schema.json -o ./project-metadata.json
Copied

The file then holds an object such as {"project_name": "Codex CLI", "programming_languages": ["Rust", "TypeScript", "Shell"]}. A schema file that cannot be read or is not valid JSON stops the run before it starts, with status 1.

Resume, fork and review

codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"
codex exec resume <SESSION_ID> "now add a test"
codex exec --sandbox workspace-write resume --last "apply the fix"
Copied

resume --last picks the newest recorded session for the current directory; add --all to look across every directory. A resumed run keeps the session’s working directory, workspace roots and sandbox, so -C, --sandbox and --add-dir go before resume to change them. A run made with --ephemeral writes no session files. Two more subcommands exist: codex exec fork <SESSION_ID> starts a new session from an old one, and codex exec review reviews the repository with --uncommitted, --base BRANCH or --commit SHA.

Exit codes

OpenAI’s docs list none, so this is what the 0.172.0 source of codex exec does, not a documented contract. Every exit it calls on failure uses status 1: when the turn ends with the status failed or interrupted (Ctrl-C sends the turn an interrupt), when an error arrives that Codex will not retry, and, before the turn starts, for a bad -c override, a config.toml or rules file that will not load, an output schema that cannot be read or is not valid JSON, a missing prompt, or the Git check. The docs add that a required MCP server (required = true) that fails to start makes codex exec exit with an error. The source calls no exit with any other status, so test for zero and treat anything else as failure; the reason is in stderr or the --json stream (turn.failed, error).

Signing in for an unattended run

codex exec reuses whatever login the CLI has saved, so a server where you ran codex login once is ready. For a single run on an API key, the docs use an inline variable:

CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"
Copied

Typed like that, the key lands in your shell history. Keep it in a file only you can read and hand it to the one command instead:

# once: paste the key and press Enter (nothing is shown or kept in history)
mkdir -p ~/.config
read -rs CODEX_KEY
(umask 077; printf '%s\n' "$CODEX_KEY" > ~/.config/codex-job.key); unset CODEX_KEY

# each run
CODEX_API_KEY="$(cat ~/.config/codex-job.key)" codex exec --json "triage open bug reports"
Copied

Keep that file out of any repository. OpenAI calls API keys “the right default for automation because they are simpler to provision and rotate”, says to set CODEX_API_KEY “only for the Codex invocation that needs it”, and warns against setting it or OPENAI_API_KEY as a job-level variable in a CI workflow that checks out or runs repository code, because build scripts, tests and dependency hooks in the same job can read it. A ChatGPT login lives in ~/.codex/auth.json, which holds access tokens: treat it like a password. Getting a key, what it bills and its errors are in the Codex API key guide, and signing in on a machine with no browser in Codex CLI on a Linux server.

From a script or cron on a server

A wrapper that keeps the key out of the crontab, bounds the run time and keeps the answer and the log apart:

#!/usr/bin/env bash
# ~/bin/codex-nightly.sh
set -euo pipefail
cd ~/projects/myrepo
mkdir -p ~/logs
# the key from the chmod 600 file above, for this one command only
CODEX_API_KEY="$(cat ~/.config/codex-job.key)" timeout 30m codex exec \
  --sandbox workspace-write \
  -o ~/logs/codex-$(date +%F).md \
  "Run the test suite, fix any failing test, and summarise what you changed" \
  < /dev/null 2>> ~/logs/codex-$(date +%F).log
Copied
chmod 700 ~/bin/codex-nightly.sh
crontab -e
# then add:
0 3 * * * $HOME/bin/codex-nightly.sh
Copied

Cron starts with a short PATH, so if codex is not found, put its full path (from command -v codex) in the script. The < /dev/null gives the run an empty stdin, so with the prompt as an argument there is nothing to wait for. The job runs the repository’s own tests with the key in its environment, and OpenAI’s docs ask that “no untrusted code runs in the same process environment”: point it only at a repository you trust. The workspace-write sandbox lets it change the files in the repository, so read the morning’s git diff before you push anything. On a Linux server the sandbox uses bubblewrap; if the log shows bubblewrap warnings, the bubblewrap errors guide has each one. For GitHub Actions, OpenAI’s own action wraps codex exec (Codex and GitHub), and from code rather than a shell, see the Codex SDK guide. The same job with Claude Code is in running Claude Code headless on a schedule, which also covers a systemd timer in place of cron.

Run Codex on an always-on developer pod.

A developer pod is a permanent cloud computer (VPS), set up and secured for you, with your pick of Claude Code, Codex, OpenCode, Pi, Hermes and OpenClaw installed. Run more agents at once than your laptop can hold, and keep them working when it’s closed. From $24 a month, built in about ten minutes.