The Forge · 11 min mission

The Codex CLI: Every Command, Flag & Slash Command

Drive Codex from the terminal like a power user — every subcommand, flag, and slash command.

clireferencecodexFact-checked 2026-06-13
On this page

Type codex and you get a chat box. That is the on-ramp, not the tool. The actual surface area is a command tree: one binary that is also a TUI, a non-interactive scripting engine, an auth manager, a session browser, an MCP client, and a cloud dispatcher. The difference between someone who "uses Codex" and someone who drives it is entirely in knowing which of those modes you're in and which flag bends it to your will.

This guide is the map. The command tree and what each branch is for; the dozen global flags that change Codex's blast radius (-s, -a, --yolo, -C, -m); the TUI shortcuts that make a senior engineer fast (@ to pull in a file, ! to drop to a shell, Ctrl+G to compose in your real editor, Tab to queue work mid-run); the slash commands grouped by what they touch; and codex exec — the part that turns Codex from a chat toy into something you pipe logs into from CI. Every command and flag below is quoted from the official reference; where something is a practitioner habit rather than a documented feature, it's tagged [P].

The shape of the binary

codex with no subcommand launches the interactive TUI. Add a subcommand and you branch into a different mode — codex exec runs head-less, codex login manages credentials, codex resume reopens a past thread. The global flags (-m, -s, -a, -C, …) work across most of these, so a flag you learn for the TUI usually means the same thing under exec. Learn the tree once and the flags compose.

CommandWhat it does
codexLaunch the interactive terminal UI (the default)
codex exec *(alias codex e)*Run Codex non-interactively — head-less, for scripts and CI
codex loginAuthenticate via OAuth (ChatGPT), API key, or access token
codex logoutRemove stored credentials from ~/.codex/auth.json
codex resumeReopen a previous session by ID, or --last for the most recent
codex forkBranch a previous session into a new thread, leaving the original intact
codex applyApply the most recent diff from a Codex cloud task to your local repo
codex cloudBrowse or run Codex cloud tasks from the terminal (cloud exec, cloud list)
codex mcpManage MCP servers — list, add, get, remove, login, logout
codex appLaunch Codex Desktop from the terminal (macOS / Windows)
codex doctorGenerate a diagnostic report when something is misbehaving
codex updateCheck for and apply CLI updates
codex completionGenerate shell completions for bash/zsh/fish
The Codex command tree. `codex` alone is the TUI; everything else is a subcommand. `codex exec` is the automation entry point; `e` is its alias. [V] all verified against the official CLI reference.

The global flags: bending the blast radius

Most subcommands accept the same global flags. Three of them — --sandbox, --ask-for-approval, and --model — are the ones you'll actually reach for daily, because together they decide how much Codex can do without asking and which brain it's using. The rest are sharp tools for specific jobs.

The two safety dials are worth internalizing as a pair. -s / --sandbox sets the filesystem/network sandbox for the commands Codex runs: read-only (look but don't touch), workspace-write (edit inside the working directory), or danger-full-access (no sandbox at all). -a / --ask-for-approval sets when Codex pauses to ask you: untrusted (ask for anything not on a safe list), on-request (Codex asks when it judges it needs to), or never (never pause). The headline shortcut --yolo is just both dials cranked to the floor at once.

FlagShortValuesWhat it does
--model-mmodel nameOverride the model set in configuration
--sandbox-sread-only · workspace-write · danger-full-accessSelect the sandbox policy for model-generated shell commands
--ask-for-approval-auntrusted · on-request · neverControl when Codex pauses to ask before running a command
--cd-CpathSet the working directory for the agent
--image-ipath[,path…]Attach one or more image files to the initial prompt
--profile-pprofile nameLayer a named profile.config.toml on top of the base config
--config-ckey=valueOverride individual configuration values inline
--add-dirpathGrant the sandbox write access to an additional directory
--ossUse a local open-source model provider (Ollama) instead of the cloud
--remotews:// · wss:// · unix://Connect the TUI to a remote app-server
--dangerously-bypass-approvals-and-sandbox *(alias --yolo)*Run every command with no approvals and no sandbox
--searchEnable live web search during the session
Global flags, with exact short/long forms and accepted values, quoted from the official reference [V]. The short flag and long flag are interchangeable.

TUI fluency: the shortcuts that make you fast

Inside the interactive session, a handful of keys separate fumbling from flow. None of them are obvious from the chat box, and all of them are documented [V]. These are the muscle-memory moves.

@ — fuzzy file search. Type @ and Codex opens a fuzzy finder over your workspace root. Keep typing to narrow, then Tab or Enter inserts the highlighted path into your message. This is how you point Codex at a file without typing the whole path or pasting its contents — far cheaper than dumping a file into chat.

! — inline shell. Prefix a line with ! to run a local shell command yourself; Codex treats the output as if you'd handed it the result. !git status, !npm test, !ls src/ — you stay in the conversation, run a quick command, and its output becomes context for the next turn without a round-trip through the model.

Ctrl+G — compose in your real editor. Ctrl+G opens the editor named by your VISUAL environment variable (or EDITOR if VISUAL isn't set) [V]. For a long, structured prompt — a multi-paragraph spec with code blocks — this beats fighting the inline composer: you write in Vim or VS Code with full editing power, save, and the text drops back into Codex.

Tab — queue a follow-up mid-run. While Codex is working, press Tab to queue follow-up text, a slash command, or a ! shell command for the next turn [V]. You don't have to wait for it to finish before lining up the next instruction. (Pressing Enter mid-run instead injects new instructions into the current turn.)

Ctrl+O — copy the last output. Ctrl+O (or the /copy slash command) copies Codex's latest completed output to your clipboard [V] — for pasting a generated snippet or message elsewhere without mouse-selecting terminal text.

a real TUI turn: @ a file, ! a command, queue with Tab
… scroll to run this session
Pull a file in with @, run a test yourself with !, then queue the next instruction with Tab while Codex works. No copy-paste, no waiting.

The slash commands, grouped

Slash commands run inside the session. There are a lot of them; grouping by what they touch makes them learnable. Every command below is documented [V]; you trigger them by typing / at the start of a line, which also opens an autocomplete menu.

Session & navigation control the conversation thread itself. /new starts a fresh conversation, /resume reopens a saved one from your session list, /fork branches the current thread, /compact summarizes the visible conversation to free up tokens, /clear resets the screen and chat, and /quit (or /exit) closes the CLI. /side (alias /btw) opens an ephemeral side conversation for a quick aside that won't pollute the main thread.

Model & task shape how Codex thinks. /model picks the active model and reasoning effort, /plan switches to plan mode for proposing a strategy before acting, /goal sets a persistent objective across turns, and /review asks Codex to analyze your working tree.

Code & files connect Codex to your repo state. /diff shows the Git diff including untracked files, /mention attaches specific files, /ide pulls in your open-editor context, and /init scaffolds an AGENTS.md for the project.

Permissions & safety adjust the dials mid-session. /permissions changes approval requirements without restarting, and /approve retries an action that auto-review denied.

UI & system tune the surface and inspect state. /status shows session config and token usage, /theme picks a syntax-highlighting theme, /personality sets a response style, /vim toggles Vim mode in the composer, /mcp lists configured MCP tools, and /copy copies the last output.

GroupCommands
Session & navigation/new · /resume · /fork · /compact · /clear · /side (/btw) · /archive · /quit (/exit)
Model & task/model · /plan · /goal · /review · /fast
Code & files/diff · /mention · /ide · /init
Permissions & safety/permissions · /approve
UI & system/status · /theme · /personality · /vim · /keymap · /mcp · /skills · /copy · /logout
Sessions & process control/ps · /stop (/clean) · /agent · /raw · /title · /statusline · /debug-config · /sandbox-add-read-dir · /feedback
The slash-command set grouped by what it touches, with exact names [V]. Type `/` to open the autocomplete menu in-session.

Background terminals, threads, and diagnostics

The last group is the one the chat box hides most completely: commands for process control — work and surfaces that outlive a single turn. Every command here is documented [V].

Codex can run experimental background terminals (builds, watchers, dev servers). /ps lists them and shows recent output so you can check status without leaving the transcript, and /stop stops all of them at once. /clean is purely an alias of /stop — not a transcript cleaner — so don't confuse it with /clear (which resets the screen and chat). When a session has more than one agent thread, /agent switches the active one so you can inspect or continue a specific thread.

The rest tune the surface and help you debug it. /raw toggles raw scrollback so a block of output copies cleanly out of the styled TUI. /title and /statusline configure what the terminal title and the footer show — you pick and reorder fields like the model, git branch, context usage, or token counts; /statusline is the persistent footer, distinct from the one-shot /status report. /debug-config prints the config-layer precedence so you can see which layer won when a setting misbehaves [V], and /sandbox-add-read-dir <absolute-path> grants the sandbox read access to one more directory — Windows only, and the path must be absolute. Finally, /feedback sends logs and diagnostics to the Codex maintainers.

Sessions live on disk as JSONL

Every Codex session is written to disk as JSONL under ~/.codex/sessions/ [V] — one JSON object per line, the full transcript and tool calls. This is not a hidden cache; it's the mechanism behind resume and fork, and it means your work survives a closed terminal.

Two subcommands read those files back. codex resume reopens an earlier thread with the same repository state — pass a session ID, or codex resume --last to jump straight to the most recent session. Add --all to consider sessions from outside the current working directory, not just this project's.

codex fork is the one to reach for when you want to try something without losing your place. It branches a previous session into a new thread, leaving the original untouched — so you can take an exploratory tangent ("what if we used Postgres instead?") and still have the clean original to come back to. Inside the TUI, /fork does the same thing live, and pressing Esc twice on an empty composer lets you edit a previous message and fork from that point.

resume vs fork — continue the line, or branch it

codex resume

Continues an existing thread in place.

  • codex resume --last reopens the most recent session
  • codex resume <SESSION_ID> reopens a specific one
  • Add --all to include sessions from other directories
  • The transcript keeps growing on the same line of history

Use it to pick up where you left off after lunch or a reboot.

codex fork

Branches a thread into a new one, original untouched.

  • codex fork (or /fork in-session) starts a parallel thread
  • The source session is preserved exactly as it was
  • You get a clean place to try a risky or exploratory direction

Use it to take a tangent without burning the known-good thread.

codex exec: Codex as a pipe

codex exec is where Codex stops being a chat app and becomes a Unix citizen. It runs non-interactively [V]: no TUI, no prompts (unless you ask for them), progress streamed to stderr and only the final message to stdout — which is precisely what makes it pipeable.

The simplest form takes the prompt as an argument:

bash
codex exec "summarize the repository structure and list the top 5 risky areas"

Because the final answer goes to stdout, you can tee or redirect it:

bash
codex exec "generate release notes for the last 10 commits" | tee release-notes.md

Stdin is a first-class input. Pipe content in and give an explicit instruction as the argument — the piped text becomes context:

bash
npm test 2>&1 | codex exec "summarize the failing tests and propose the smallest likely fix"

Or let stdin be the whole prompt by omitting the argument or using the - sentinel:

bash
cat prompt.txt | codex exec -
printf "Summarize this error:\n\n%s" "$(tail -n 200 app.log)" | codex exec -

That npm test 2>&1 | codex exec … line is the whole pitch in one command: a failing build pipes its own output into Codex and gets back the smallest likely fix, no human in the loop.

FlagShortWhat it does
--jsonPrint newline-delimited JSON events — one JSON object per line, with event type and data
--output-last-message-oWrite the assistant's final message to a file (while still printing to stdout)
--output-schemaPass a JSON Schema file; the final response is constrained to match it
--ephemeralRun without persisting session files — nothing written to ~/.codex/sessions/
--sandbox workspace-write-sAllow edits inside the working dir (exec defaults to read-only)
--skip-git-repo-checkAllow running outside a Git repository
The `codex exec` flags that matter for automation, quoted from the non-interactive docs [V]. `--sandbox` defaults to read-only under exec, so pass `workspace-write` when you want edits.

A worked exec pipeline: structured, validated output

  1. Define the shape you want

    Write a JSON Schema describing the response — e.g. schema.json requiring { name, language, riskAreas[] }. This is your contract: Codex must return data matching it.

  2. Run exec with the schema and an output file

    Pass both --output-schema and -o so the result is validated and saved:

    bash
    codex exec "Extract project metadata" \
      --output-schema ./schema.json \
      -o ./project-metadata.json

    The final message is constrained to your schema and written to project-metadata.json — ready for jq or a downstream step.

  3. For event-level visibility, add --json

    --json emits newline-delimited JSON events to stdout — every tool call, message, and state change as a parseable line. Pipe it into jq to watch or log exactly what Codex did, which is how you build observable CI jobs instead of opaque ones.

  4. Resume the exec thread if needed

    A non-interactive run is still a session. Continue it with codex exec resume --last "fix the race conditions you found" or by ID: codex exec resume <SESSION_ID>. Add --ephemeral on the original run when you explicitly don't want it persisted.

Auth, briefly

Before any of this works you authenticate once. codex login runs OAuth through your ChatGPT account by default [V] — it opens a browser, you sign in, done. For API-key billing instead, codex login --api-key signs in with an OpenAI platform key. Headless boxes have two escape hatches: codex login --device-auth (a one-time code you type in a browser elsewhere) and piping a token in: printenv CODEX_ACCESS_TOKEN | codex login --with-access-token.

Credentials cache at ~/.codex/auth.json (or your configured $CODEX_HOME) [V]. Check state with codex login status; wipe it with codex logout. Treat auth.json like a password — it holds live access tokens.

The senior-engineer move: a nightly triage job

Here's the pattern that pays for learning all of this. You want a cron job that, every morning, reads yesterday's error logs and files a triage note — no human in the loop, but observable enough that you trust it.

bash
#!/usr/bin/env bash
set -euo pipefail
 
tail -n 500 /var/log/app/errors.log | codex exec - \
  --sandbox read-only \
  --output-schema ./triage-schema.json \
  -o "./triage/$(date +%F).json" \
  --json 2> "./triage/$(date +%F).events.jsonl"

Every flag is load-bearing. codex exec - makes the piped log the prompt. --sandbox read-only guarantees the job cannot touch the filesystem — it's analysis only, so even a prompt-injected log line can't make it write or run anything. --output-schema forces the answer into a shape your dashboard can ingest. -o saves that structured result per day. --json on stdout (redirected to an events file via the 2>) gives you a full replayable trace of what Codex did. The result: an autonomous job with a hard safety floor and a complete audit log — the difference between "we let an AI read our logs" and "we have an accountable, sandboxed triage pipeline."

Build the command, then run it

You now have the whole tree: codex for the TUI, codex exec for pipes, the safety dials (-s, -a, --yolo), the navigation (resume, fork), and the in-session vocabulary (@, !, Ctrl+G, Tab, the slash commands). The fastest way to cement it is to assemble a real command and read back exactly what each flag will do — which is what the builder below is for.

Build your codex command

Build a codex command

Compose a real codex invocation — base command, model, sandbox, approval and optional flags. The command on the right rewrites itself as you click, every flag is explained, and the matrix shows exactly what your sandbox × approval pair allows and blocks.

Base command

codex opens the TUI; codex exec is the non-interactive runner for CI.

Prompt

The task, passed as a trailing argument. Clear it to omit.

Model

-m takes any provider model id. Two Codex-family examples shown.

Sandbox · -s

How much of the machine the agent can touch.

Edits files in cwd + tmp. Network off unless enabled in config.

Approval · -a

When Codex pauses to ask you before acting.

Runs freely in the sandbox; only asks when a command fails.

How to set sandbox + approval

The dedicated -s/-a flags, or the equivalent inline config overrides.

Emits the dedicated -s / -a flags.

Optional flags

Toggle on what the run needs. Flags that take a value reveal an input.

exec output · CI only

codex exec can emit machine-readable output for the next pipeline step.

terminal
$ codex exec -m gpt-5.3-codex -s workspace-write -a on-failure --json 'Fix the failing tests and explain why.'

What each flag does

  • -m gpt-5.3-codex Picks the model. -m accepts any provider model id; gpt-5.3-codex is a Codex-family choice.
  • -s workspace-write Sandbox: workspace-write Edits files in cwd + tmp. Network off unless enabled in config.
  • -a on-failure Approval: on-failure Runs freely in the sandbox; only asks when a command fails.
  • --json Streams structured JSONL events to stdout — parse them in CI instead of scraping the TUI.

Sandbox × approval

Rows = sandbox (-s), columns = approval (-a). Your pair is lit.

UntrustedOn failureOn requestNeverReadWriteFull

workspace-write + on-failure: edits cwd + tmp; runs freely in the sandbox; only asks when a command fails.

Pick a mode, a sandbox, an approval policy, a model and the extras — and watch the exact command assemble, with each flag explained.

Knowledge check

You want a CI job to read a failing test log piped on stdin, return JSON your dashboard can parse, and be physically unable to modify any files. Which invocation fits?

Reach the end and this star joins your charted sky.