Codex CLI: A Concise Guide

From install and login to codex exec automation: interactive usage, session management, code review, sandbox and approval modes, config, and MCP at a glance.

#Codex#CLI#Tutorial

OpenAI Codex CLI is an AI coding assistant that lives in your terminal: it reads code, edits files, runs commands, and reviews changes — interactively, or scripted and wired into CI. This guide covers the command-line tool only (including codex exec automation). It does not cover the desktop app, IDE extensions, or the cloud product.


1. Install and update#

Pick whichever of the three install paths suits you:

Terminal window
# Option 1: npm (most common)
npm install -g @openai/codex
# Option 2: Homebrew (macOS)
brew install codex
# Option 3: official standalone installer (macOS / Linux)
curl -fsSL https://chatgpt.com/codex/install.sh | sh
# Upgrade (for an npm install, just rerun the install command)
npm install -g @openai/codex@latest
# Check the version
codex --version

Other package managers work too: yarn global add @openai/codex / bun install -g @openai/codex / pnpm add -g @openai/codex.


2. Login and authentication#

The first run prompts you to log in, but you can also manage credentials by hand:

Terminal window
# Interactive login (ChatGPT account OAuth, or an API key)
codex login
# Device-code flow (handy on remote / browserless machines)
codex login --device-auth
# Log in with an API key from an environment variable (handy in CI)
printenv OPENAI_API_KEY | codex login --with-api-key
# Show the current login status
codex login status
# Log out (clears local credentials — remember this on shared machines)
codex logout

3. Quick start (interactive mode)#

cd into a project and start it:

Terminal window
# Launch the interactive TUI (no arguments)
codex
# Start with an initial prompt
codex "help me understand this project's architecture"
# Attach an image (screenshot / mockup / error dialog)
codex -i error.png "find the problem from this error screenshot"
# Set the working directory
codex -C ~/projects/api "review this service"
# Two good first prompts
# Tell me about this project
# Find and fix bugs in my codebase with minimal, high-confidence changes.

Beginners should do two things first:

Terminal window
/init # have Codex generate an AGENTS.md instruction file (type it inside the TUI)

Then keep an eye on its edits with git status / git diff, and use Git checkpoints so you can always roll back.


4. Slash commands in interactive mode#

Type / in the TUI composer to open the command menu. The usual suspects:

CommandWhat it does
/initScaffold an AGENTS.md project instruction file in the current directory
/statusInspect the session config (model, approval policy, token usage, remaining context)
/permissionsAdjust the approval / permission mode (Read Only, Auto, …)
/modelSwitch model and reasoning effort
/fastToggle the model’s fast service tier (on / off / status)
/planEnter plan mode: produce a plan before touching anything
/goal <objective>Set / view / pause / clear the task objective
/reviewRun one code review over the workspace changes
/diffShow the Git diff (untracked files included)
/mention <path>Add a file to the conversation context
/compactCompress earlier turns to free up context
/newStart a fresh conversation in the same session (resets context)
/resumeResume a past conversation from the session list
/forkCopy the current conversation into a new thread (to explore alternatives)
/sideOpen a throwaway side conversation without derailing the main thread
/agentSwitch between / inspect subagent threads
/skillsBrowse and use local skills
/mcpList the configured MCP tools (/mcp verbose for details)
/apps / /plugins / /hooksBrowse apps (connectors) / plugins / lifecycle hooks
/idePull the file and selection open in your IDE into the next prompt
/vim / /keymap / /theme / /statusline / /titleComposer Vim mode / keymap / theme / status line / terminal title
/personalitySet the communication style (friendly / pragmatic / none)
/memoriesConfigure memory generation and enablement
/ps / /stopInspect / stop background terminal tasks
/copyCopy the most recent reply (same as Ctrl+O)
/rawToggle raw scrollback mode, which makes long output easier to copy
/debug-configPrint config-layer diagnostics (when a setting refuses to take effect)
/feedback / /logout / /quit (/exit)Feedback / log out / quit

Tip: while a task is running you can still queue a slash command with Tab; it runs once the current turn finishes.


5. Non-interactive mode: codex exec (scripts / CI)#

codex exec (alias codex e) skips the TUI, runs once, and exits — built for automation and pipelines:

Terminal window
# Basic use: one task, output straight to the terminal
codex exec "fix the failing unit tests"
# Read the prompt from stdin
echo "add an install section to the README" | codex exec -
# Pipe data in and pass a prompt at the same time
cat error.log | codex exec "diagnose this stack trace and suggest a fix"
# JSON event stream (easy to process with jq and friends)
codex exec --json "list the 5 riskiest files" | jq
# Save the final reply to a file
codex exec "write release notes for the last 10 commits" -o notes.md
# Force a structured JSON reply
codex exec "extract project metadata" --output-schema schema.json -o meta.json
# Resume the previous exec session to follow up
codex exec resume --last "now fix the issues you just found"
# Quiet, approval-free run in CI
codex exec --approve-for-me --quiet "update the CHANGELOG and prep the next release"

A GitHub Actions example:

.github/workflows/codex.yml
name: Codex Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: openai/codex-action@v1
with:
openai-api-key: ${{ secrets.OPENAI_API_KEY }}
prompt: "Review the changes in this PR and point out potential problems"

Useful environment variables:

VariableWhat it does
OPENAI_API_KEYAPI key (or store one via codex login)
CODEX_QUIET_MODE=1Quiet mode: less interactive noise
CODEX_DISABLE_PROJECT_DOC=1Stop loading project docs such as AGENTS.md
DEBUG=truePrint full API requests/responses (for troubleshooting)
CODEX_TOKEN_LOG=~/tokens.csvLog token usage for every request

6. Session management: resume / fork#

Codex stores sessions locally, so you can always return to earlier work:

Terminal window
# Pick a past session interactively
codex resume
# Jump straight back into the most recent session
codex resume --last
# Fork a new session off an existing one (keep the original, branch out)
codex fork --last

Inside the TUI, /resume and /fork do the same.


7. Code review: codex review#

Terminal window
# Review the uncommitted workspace changes (workspace untouched)
codex review
# Review against a base branch (PR style)
codex review --base main
# Review a specific commit
codex review --commit HEAD~1
# Review a specific PR
codex review --pr 123

8. Common CLI flags#

FlagShortDescription
--model <name>-mPick a model, e.g. -m gpt-5-codex (availability depends on your plan)
--sandbox <mode>-sSandbox policy: read-only / workspace-write / danger-full-access
--ask-for-approval <policy>-aApproval policy: on-request (ask as needed) / never (stop asking)
--full-autoPreset combo: workspace-write + on-request, a low-friction automatic mode
--yoloAlias for --dangerously-bypass-approvals-and-sandbox: no sandbox, no approvals — dangerous, hardened environments only
--image <path>-iAttach images to the initial prompt; separate multiple paths with commas
--cd <path>-CSet the agent’s working directory
--add-dir <path>Grant write access outside the main workspace; repeatable
--config <key=value>-cOverride one config value for this run (TOML-parsable values win)
--profile <name>-pLoad a profile from ~/.codex/<name>.config.toml
--searchEnable live web search
--ossUse a local open-source model (LM Studio / Ollama)
--local-provider <name>Select the local provider: lmstudio or ollama
--enable/--disable <feature>Force a feature flag on or off (same as -c features.x=true/false)
--no-alt-screenDisable the TUI alternate screen (steadier under tmux / scripts)
--strict-configError out on unknown config fields (good for catching typos)
--remote <ws://...>Connect to a remote app-server (experimental)
--version / --help-V / -hVersion / help
PROMPT (positional)Optional initial prompt; omit it to land straight in the TUI

Every subcommand takes --help for the most accurate, up-to-date flags — codex exec --help, for instance.


9. Sandbox and approval modes (the security core)#

Codex isolates the commands the model generates with native OS sandboxing: Seatbelt on macOS, Bubblewrap on Linux, restricted tokens on Windows.

Sandbox modes (-s):

ModePermissionsTypical use
read-onlyRead only: no writes, no networkSafe exploration, code audit
workspace-writeRead/write inside the working directoryDay-to-day development (the default in a Git repo)
danger-full-accessFull accessSystem administration tasks, used with care

Approval policies (-a):

PolicyBehavior
on-requestThe model pauses to ask when needed (default)
neverStops asking; commands just run

Common combinations:

Terminal window
# Safe exploration: read-only plus asking on request
codex -s read-only -a on-request "audit this project for injection flaws"
# Everyday coding (the default behavior)
codex -s workspace-write -a on-request "refactor the auth module and run the tests"
# Automatic mode: no approvals inside the sandbox
codex --full-auto "run the tests and fix the failing cases"
# Dangerous mode (only inside a CI sandbox or a disposable container)
codex --yolo "set up the whole dev environment from scratch"

You can change course mid-session with /permissions at any time.


10. Models and reasoning effort#

Terminal window
# Pick a model on the command line
codex -m gpt-5-codex "refactor this module"
# Override reasoning effort for one run
codex -c model_reasoning_effort=high "design a database migration plan"

The model list is not baked into the CLI; it loads dynamically for your ChatGPT plan or API account. Inside the TUI, /model opens a picker for both model and reasoning effort, and /fast toggles the fast service tier.


11. Configuration: config.toml / profiles / AGENTS.md#

Config locations and precedence (high → low):

CLI flags (-c key=value)
> Profile (~/.codex/<name>.config.toml)
> Project config (.codex/config.toml)
> User config (~/.codex/config.toml)
> System config
> Defaults

A user config example (~/.codex/config.toml):

model = "gpt-5-codex"
model_reasoning_effort = "high"
approval_policy = "on-request"
sandbox_mode = "workspace-write"
web_search = "cached" # or "live" / "off"

Project-level config (shared with the team, committed to the repo): create .codex/config.toml at the project root to give different projects different models and sandbox policies.

Profiles (flipping between environments):

Terminal window
codex --profile ci "run the checks" # uses ~/.codex/ci.config.toml

AGENTS.md project instructions (the equivalent of Claude Code’s CLAUDE.md) merge bottom-up in this order:

~/.codex/AGENTS.md # personal global instructions
repo root AGENTS.md # shared project conventions (commit it to Git)
subdirectory AGENTS.md # per-directory / per-feature notes

Use /init to generate the scaffold, then fill it in with your team’s conventions, for example:

## Project conventions
- Use TypeScript strict mode
- Every function needs a JSDoc comment
- Keep test coverage above 80%

12. MCP and extensions#

Terminal window
# List the configured MCP servers
codex mcp list
# Add a local MCP server
codex mcp add context7 -- npx -y @upstash/context7-mcp
# Connect to a remote HTTP MCP server (Figma, for example)
codex mcp login figma
# Expose Codex itself as an MCP server
codex mcp-server

Inside the TUI, /mcp lists the tools this session can call.


13. Recipes for common tasks#

Terminal window
# Understand an unfamiliar project
codex "tell me what this project does and what the main modules are"
# Fix a bug
codex "find and fix bugs in my codebase with minimal, high-confidence changes"
# Refactor
codex "refactor the Dashboard component to React Hooks and get the tests passing"
# Write tests
codex "write unit tests for utils/date.ts"
# Generate a migration / scaffold
codex "generate the SQL migration that adds a users table"
# Bulk rename
codex "rename every *.jpeg to *.jpg with git mv and update the references"
# Explain a regex
codex "explain what this regex means: ^(?=.*[A-Z]).{8,}$"
# Security audit
codex "scan for vulnerabilities and write a security review report"
# Update the CHANGELOG in CI
codex exec --full-auto --quiet "update the CHANGELOG and prep the next release"
# Build a UI from a screenshot
codex -i mockup.png "implement this page from the mockup"
# Look up the current best practice online
codex --search "find the currently recommended best-practice Vite config"
# Review your own changes before committing
codex review --base main

14. Best practices and gotchas#

  1. Git checkpoints are your lifeline: Codex edits code directly, so commit before and after a task and git reset if things go sideways.
  2. Start in Read Only: point codex -s read-only at a new project first to explore without writes, then loosen up once you know how it behaves.
  3. Prefer --full-auto over --yolo: the former stays inside the sandbox, the latter has no protection at all.
  4. Use codex exec for CI and automation: pair it with --json / -o / --output-schema for machine-readable output.
  5. Pin conventions in AGENTS.md: writing team rules down once costs fewer tokens and behaves more consistently than repeating them every prompt.
  6. /compact when context grows: compress the conversation after long tasks so you don’t burn the context window early.
  7. codex logout on shared machines: clear the local credentials when you’re done.
  8. When a flag is unclear, read the help: whatever codex --help and codex exec --help print for your installed version is the truth (the CLI moves fast; model names and feature flags change with releases).

Appendix: cheat sheet#

install npm install -g @openai/codex
login codex login / codex login status / codex logout
interactive codex ["prompt"] / codex -i image "prompt"
scripting codex exec "task" / --json / -o file / stdin pipe
sessions codex resume [--last] / codex fork --last
review codex review [--base main | --commit | --pr 123]
security -s read-only|workspace-write|danger-full-access
-a on-request|never / --full-auto / --yolo (dangerous)
models -m <model> / -c model_reasoning_effort=high
directories -C <path> / --add-dir <path>
config -c key=value / --profile <name> / ~/.codex/config.toml
instructions /init generates AGENTS.md
in-session /status /permissions /model /diff /review /compact /new /quit
License

CC BY-NC-SA 4.0 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.