Skip to content

Getting Started with the CLI

📚 Series Navigation: The previous article 07 · Desktop App Overview got you familiar with the clicks in the graphical interface—reviewing diffs, running tasks side-by-side, and visual approvals. This article switches gears to dive into the terminal, explaining how to use the codex command: parsing command structures, understanding the interactive interface, and learning common flags and slash commands. The next article 09 · IDE Extensions (VS Code, etc.) will pack it into your editors.

They say "graphical interfaces are friendliest to beginners, avoid the command line if you can"—but to be honest, when it comes to Codex, this advice is only half true.

Having used both entries for nearly half a year, my conclusion is clear: the Desktop App is for "viewing," and the CLI is for "doing." If you want to monitor every edit visually or run five tasks side-by-side, the Desktop App is indeed pleasant. But once you want to integrate Codex into your workflow—writing scripts to review code automatically every morning, running it on cloud servers without graphical interfaces, or packing it into CI pipelines—the Desktop App cannot do any of these; they rely entirely on the CLI.

What's even more counterintuitive: the CLI's "black window" is not that dark. Launching the Codex CLI does not leave you staring at a single flashing cursor; it enters a full-screen interactive interface called TUI (Terminal User Interface)—complete with a conversation zone, input box, and status bar, with an information density similar to the Desktop App, just operated entirely via keyboard. The first time I opened it, I paused: this isn't a command line; it is an "app living inside the terminal."

So this article is not about discouraging or hyping. It does only one thing: thoroughly explain the codex command, helping you move from "afraid to type" to "typing smoothly."

After reading this article, you will get:

  • A structural diagram of the codex command—how a command is split, and where subcommands and flags belong
  • What to look for and how to operate the three areas of the interactive TUI (conversation zone / input box / status bar)
  • A quick lookup table of the most common flags (--model, --sandbox, --cd, --search, -i...), all verified against the official cli/reference
  • Several daily slash commands and keyboard actions, along with a minimal verification flow to follow
  • The dividing line between interactive runs (monitoring step-by-step) and exec runs (one-shot execution), so you know when to use which

⚠️ All specific commands, flags, and default behaviors mentioned below are based on the Codex official documentation; model names and subscription plans are subject to change and should match what is actually displayed on your local system.


01 Let's Deconstruct the codex Command

Many beginners fear the command line, not because of typing, but because they don't know what those long strings of dashed terms meancodex exec --sandbox workspace-write --model xxx "do something" looks like hieroglyphics.

In fact, the structure is highly regular. First, the conclusion: the codex command is built from at most four parts—the main command, subcommands, flags, and prompts. Recognize these four parts, and you can break down any long command at a glance.

Analogy: Ordering a customized coffee at a cafe. codex is you walking in and shouting "give me a coffee" (the main command); choosing "iced Americano" or "latte" is the subcommand (exec, resume, cloud... a different way to run); "less ice, extra espresso, oat milk" are the flags (those starting with --); and finally, what you want done—"check this code for me"—is the prompt. A sentence of four parts, where missing parts are fine, but the order is fixed.

Deconstructed, it looks like this:

text
codex   [subcommand]   [flags...]   ["prompt"]
  │         │             │            │
Command   Run Mode    Parameters    Task to Do

Breaking down each part:

  • Main Command codex: Once installed, this command is available in your terminal. Running codex alone enters the interactive TUI.
  • Subcommand: Switches the "run mode." For example, codex exec runs non-interactively (exiting after a single run, without entering the TUI), codex resume continues the last session, and codex login logs you in. Omitting the subcommand defaults to entering the interactive TUI.
  • Flags (flags): Switches starting with -- or - to adjust parameters. For example, --model switches models, --sandbox adjusts sandboxes, and --cd switches working directories. Most flags have both long and short versions (--model equals -m).
  • Prompt: A quoted sentence describing the task you want done. It is optional—omit it to enter the TUI and chat slowly, or include it to have it start working on the prompt immediately.

A few examples to start with, from simple to complex:

bash
# Omit all, enter interactive TUI
codex
bash
# Include a prompt; starts working on it immediately after entering the TUI
codex "Explain the structure of this project"
bash
# Switch model + specify working directory
codex --model gpt-5.5 --cd ~/my-project "Complete the README"

⚠️ The gpt-5.5 above is only illustrative. Specific model names and recommendations change quickly with versions; run /model to see what is actually listed on your local system instead of copying hardcoded names.

See that? Even the most complex commands are just combinations of these four blocks. All subsequent usages build upon this skeleton.

💡 Summary in one sentence: The codex command consists of four parts—main command + subcommand (run mode) + flags (parameters) + prompt (task). Recognize this skeleton to turn hieroglyphics into fill-in-the-blanks.


02 Entering the Interactive TUI: Three Areas to Know

Running codex alone launches the TUI. Beginners often get confused on their first look: where do I speak? Where is its progress shown?

Don't panic; it is the same concept as the Desktop App. You only need to know three areas: the conversation zone, the input box, and the status bar. The rest of the scrolling text is just its report to you, which you can scan.

Analogy: Watching a livestream. The main area is the host presenting (the conversation zone, where Codex lists its plan, prints code, and shows diffs); the input box at the bottom is where you type comments (the input box, where all your prompts enter); and the small text in the corner shows "viewer count, current product" (the status bar, showing the active model, context usage, and directory). You don't have to watch the whole screen to follow the livestream; just watch these three areas.

Codex CLI TUI: conversation zone, input box, status bar

Breaking down each area:

  • Conversation Zone (the large middle area): Codex's "main stage." It explains its steps here, prints modified code blocks, and shows Git diffs—with syntax highlighting for both code and diffs (specially added by the developers for readability). Scan here to review what it edited.
  • Input Box (at the bottom): Your only entry point to talk to Codex. Type prompts, paste code, attach screenshots, or run slash commands all in this line.
  • Status Bar / Footer (the small text below the input box): Displays session readings—active model, remaining context window, current directory, and Git branch. The official docs mention /statusline to let you customize which fields to display and how to sort them.

Here is a trap beginners always fall into: the screen suddenly gets scrambled or half-blank. Don't assume it crashed. This usually happens when running Codex in tmux and switching windows, resulting in terminal garbage. Running Ctrl+L forces a redraw of the screen, without losing the conversation.

I was running Codex on a remote server via SSH last year, and the network hiccuped, messing up the TUI layout. I was about to run Ctrl+C to restart, but remembered this shortcut—pressing it restored the layout instantly. If I had restarted, I would have lost that long context.

However, there is a Codex-specific command that is easily confused with Ctrl+L:

Ctrl+L redraws the screen but keeps the conversation context; the slash command /clear clears the screen and starts a brand-new conversation—erasing the context. One is "cleaning the blackboard," and the other is "switching to a new blackboard." Do not mix them up.

💡 Summary in one sentence: For the TUI, just remember "conversation zone to review edits, input box to speak, status bar to check readings." Press Ctrl+L to redraw a scrambled screen (keeps conversation), and do not confuse it with /clear which clears the conversation context.


03 Most Common Flags: Eight for Daily Use

Flags are the soul of the CLI, but memorizing all of them in the official cli/reference is unnecessary. I have selected eight flags that you will actually use daily, leaving the rest to look up as needed.

Analogy: Dials on a camera. A DSLR has dozens of buttons, but you spend 90% of your time adjusting just a few—aperture, shutter speed, and ISO. Flags are the same: master the high-frequency ones first, and treat the rest as "advanced mode" to look up in the manual when needed.

The table below is verified against the official cli/reference:

Flag (Long / Short)What It Is ForExample
--model / -mTemporarily switch model for this runcodex -m gpt-5.5 "Refactor this function"
--sandbox / -sChoose sandbox policy (read-only / workspace-write / danger-full-access)codex -s read-only "Review this code, do not edit"
--ask-for-approval / -aChoose approval policy (untrusted / on-request / never)codex -a on-request "Fix this bug"
--cd / -CSpecify working directory directly without cd firstcodex --cd ~/proj "Explain this project"
--add-dirExpose an additional directory as writable (repeatable)codex --cd app --add-dir ../shared
--image / -iAttach an image (screenshot / design mockup)codex -i error.png "What is this error?"
--searchEnable real-time web search for this runcodex --search "Write using the latest API"
--ossSwitch to local open-source models (requires Ollama running)codex --oss "Write a script offline"

A few worth noting:

--cd is my favorite. I used to have to cd into a directory first and then run codex to start it on a project. Later, I realized codex --cd ~/my-project "..." does it in one step, launching it directly in that directory, and the TUI header displays the path so I don't get lost.

--sandbox and --ask-for-approval are the core dials to control "what it can edit and whether it asks you." These were explained in Article 02 (sandbox manages ability, approval manages prompting); here, just know they can be temporarily specified on the command line. The low-risk daily combo is --sandbox workspace-write paired with --ask-for-approval on-request—the fence is locked, prompting you only when stepping out. What each tier means and how to save them in config files is covered in Article 15 "Permissions, Sandboxes, and Approvals", so we won't repeat it here.

--search defaults to cache: Codex enables web search by default, but uses pre-indexed cache results maintained by OpenAI (reducing the risk of prompt injections from malicious sites); adding --search switches to real-time. If you need the latest data, add --search to query live. Note: whether cached or live, web search results should always be treated as untrusted sources.

The most dangerous flag must also be mentioned, but do not use it yet:

⚠️ --dangerously-bypass-approvals-and-sandbox (alias --yolo) bypasses all approvals and sandboxes, running every command directly without prompting. The official docs state: "only use in environments with external isolation." In the beginner stage, pretend it doesn't exist—using it by mistake may let Codex run wild across your entire machine.

💡 Summary in one sentence: Master the eight high-frequency flags—-m to switch models, -s / -a to adjust permissions, --cd / --add-dir to target directories, -i to attach images, and --search to search live; pretend dangerous flags like --yolo do not exist.


04 Slash Commands: Remote Control Buttons in the Session

Flags are typed on the command line before starting; once inside the interactive session, if you want to adjust settings mid-conversation, you use slash commands (slash commands)—typing / in the input box brings up a menu.

Analogy: Function buttons on a TV remote. When the TV is on, you don't turn it off and on again to switch channels or adjust volume—you use the remote. Slash commands are the remote control for your Codex session: adjust settings on the fly without exiting or restarting. Switch models, modify permissions, clear context, or review changes with a single command.

The official CLI includes many slash commands (type / to explore). For the beginner stage, lock these into your muscle memory first:

Slash CommandWhat It DoesWhen to Use
/modelSwitch model (and reasoning intensity) mid-sessionWhen you want a stronger or faster model
/permissionsSwitch approval mode (Auto / Read Only / Full Access)When you want to loosen or tighten edit permissions
/statusView session details (model, approval policy, writable directories, remaining context)When you want to verify the active configurations
/diffView Git diff (including untracked files)Review exactly what was changed before committing
/compactCompress the conversation history into a summary to free up contextWhen the session is long and context is filling up
/reviewHave a separate review agent review your changesWhen you want a "second pair of eyes" to review code
/initGenerate a skeleton AGENTS.md file in the current directoryWhen you want to set project rules and conventions
/clearClear the screen and start a brand-new conversationWhen you want to switch topics completely

Note: Typing $ in the input box allows you to invoke Skills; enabled Skills also appear in the slash command menu. /goal may require enabling features.goals = true in config.toml or running codex features enable goals (subject to official docs).

My most common command is /status—when running a long task, running it tells me how much context has been burned and how much quota is left. Since Codex quota is billed by token (Article 04), /status is your fuel gauge.

💡 Summary in one sentence: Use slash commands as a remote control inside the session; /model to switch models, /permissions to adjust permissions, /status to view state, and /diff to inspect edits are your daily tools. You can use Tab to queue commands while a task is running.


05 Common Keyboard Actions

Besides slash commands, there are a few keyboard actions that serve as TUI shortcuts. Here are the ones from the official docs that you will use daily:

Keyboard ActionWhat It Does
Ctrl+CInterrupt current operation; you can also use /exit to close the session
Ctrl+LRedraw screen (clears TUI layout but keeps conversation)
/ (Up / Down arrows)Scroll through prompt history in the input box (including attached image placeholders)
Ctrl+RSearch prompt history backwards; press Enter to select, Esc to cancel
Ctrl+OCopy Codex's last completed output (equivalent to /copy)
TabQueue the next prompt / slash command / ! command while a task is running
Esc Esc (when input is empty)Go back and edit your previous message; press again to go further back, and Enter to branch from there
Ctrl+GWrite long prompts in an external editor, returning the text to the input box

Let's expand on two highly useful ones:

The ! prefix—run a shell command quickly without disturbing Codex. Typing ! at the start of the input box followed by a command (like !ls or !git status) runs that command directly in your shell. The official docs state that Codex collects the command output as "user-provided command output" into the context, respecting your sandbox and approval settings. Why is it useful? If you want to check the repository state without invoking Codex to "explain" it (burning tokens)—!git status gets it instantly, and Codex "sees" it too, so you can continue the conversation based on that state.

text
!git status

Ctrl+G to write long prompts in an editor. If you hate typing multi-line, complex requirements in a tiny input box, press Ctrl+G. Codex will launch the editor specified in your VISUAL environment variable (or EDITOR if not set). Write your prompt there, save, and close; the text is automatically returned to the TUI input box. I do this for all formatted, long prompts.

Let's also mention the @ prefix: typing @ in the input box triggers a fuzzy search for files in the workspace. Press Tab or Enter to insert the selected file path into your message—ideal for pointing Codex to a specific file without describing it in plain text.

Platform difference warning: these keymaps may behave slightly differently depending on your terminal / system. Codex provides /keymap to view and customize TUI keymaps. You can change them if they feel awkward, but master the defaults first.

💡 Summary in one sentence: The most common keyboard actions are ! to run shell commands, @ to fuzzy search files, Ctrl+G to write long prompts in an editor, Tab to queue tasks, and Ctrl+O to copy output. Use /keymap to customize keys, but master the defaults first.


06 Hands-on: Running the CLI in Five Minutes

Reading is easily forgotten. Here is a minimal verification flow that does not rely on a complex project; just create an empty folder to run it. Open your terminal and follow along.

Haven't installed the Codex CLI yet? Go to Article 03 "Installation and Login" to install it. Verify success by running codex --version.

Step 1: Create an empty directory, enter it, and launch.

On Mac / Linux, run (on Windows PowerShell, replace mkdir -p with mkdir):

bash
mkdir -p ~/codex-cli-demo && cd ~/codex-cli-demo
codex

Expected output: The full-screen TUI launches, displaying the conversation zone in the middle, the input box at the bottom, and the status bar text below it.

Step 2: Check current configurations with /status.

Type in the input box:

text
/status

Expected output: Codex prints a summary of the active session—active model, approval policy, writable directories, and remaining context window. Check this to know your current settings.

token-tracker displaying usage: project name, remaining tokens, context usage, active model

Community tools like token-tracker can present similar information graphically (see image above), showing fields like project name, remaining tokens in the 5-hour window, weekly remaining tokens, context window percentage, and active model.

Step 3: Test running a command with !.

Type ! at the start of the input box, followed by the command:

text
!echo hello-codex-cli

Press Enter. Expected output: The terminal prints hello-codex-cli directly, and this command and its output are collected into the conversation context—proving the ! shell mode works without invoking Codex to "explain" it.

Step 4: Scroll through prompt history with .

With the input box empty, press the Up arrow .

Expected output: Your previous command !echo ... is recalled in the input box. This is your prompt history, saving you from retyping instructions. Clear the input box.

Step 5: View Git diffs with /diff (and let it do some work).

First, ask it to do a small task that modifies a file:

text
Create a file hi.txt with the text "hello from codex cli" inside.

It may pause to request approval (depending on your approval policy); select approve. Once done, run:

text
/diff

Expected output: Codex lists the Git diff, including the untracked new file hi.txt. This is the standard review action before committing.

Step 6: Exit.

text
/exit

Expected output: Exits the TUI session, returning to your regular terminal. (Pressing Ctrl+C also interrupts / exits.)

By running these six steps, you have verified the TUI zones, /status, ! shell commands, prompt history, /diff, and exiting.

⚠️ Note: If it didn't pause to ask in Step 5 and created the file directly, it means your approval policy is loose (by default, writing files in the workspace is allowed in Auto mode)—this is not a bug; the sandbox + approval are working as designed. To see it pause and ask, switch to Read Only using /permissions and ask it to create a file again.

💡 Summary in one sentence: Follow these six steps to verify the TUI zones, /status, ! commands, prompt history, /diff reviews, and /exit in your muscle memory. It works much better than reading tables.


07 Interactive vs. exec: Monitoring or One-Shot Execution

Let's discuss a CLI-exclusive capability that the Desktop App cannot offer—non-interactive runs via codex exec.

The first six sections focused on "interactive" runs: running codex to enter the TUI, chatting, and reviewing each step. But some tasks do not require your presence—such as "running code reviews on yesterday's commits automatically every morning" or "running tests and fixing failures in CI." For these "one-shot prompt, run, and exit" tasks, exec (alias codex e) is the tool.

Analogy: Dining in vs. ordering takeout. Interactive runs are like dining in—you sit at the table, dishes are served one by one, and you tell the chef "make this saltier." exec runs are like ordering takeout—you place the order (a prompt), the kitchen cooks it behind closed doors, and it is delivered to your door (outputs printed to stdout) without you being present. Use dining in (interactive) when you want to monitor and adjust; use takeout (exec) for batch automation.

A minimal example:

bash
codex exec "Review current changes and list potential bugs"

It streams the final result to your terminal and exits—without entering the TUI or waiting for your inputs.

Useful flags for exec (verified against the official cli/reference):

exec FlagWhat It Is For
--model / -mSpecify which model to use for this run
--jsonOutput as line-by-line JSON events (for script parsing)
--output-last-message / -oWrite the final message to a file
--skip-git-repo-checkAllow running in non-Git directories (convenient for temp directories)
--ephemeralDo not persist the session history to disk

Compare interactive and exec side-by-side to choose:

DimensionInteractive (codex)Non-Interactive (codex exec)
Post-run stateEnters TUI, waits for next promptExits immediately after printing output
Suitable forExploration, debugging, multi-turn dialogueScripts, CI, batch runs, scheduled tasks
Requires presence?Yes, to review and promptNo, drop-and-run
Output formatVisualized in TUIStreamed to stdout, optionally --json for scripts
Typical scenario"Refactor this function, let's adjust as we go""Generate a changelog automatically"

My real-world split: I use interactive runs for tasks that need debugging and monitoring; for slow, long tasks like "run the test suite and fix failures," I write a script using codex exec --sandbox workspace-write and let it run. The official docs suggest a useful combo for CI: --json paired with --output-last-message—the former gives machine-readable progress logs, and the latter extracts the final natural language summary.

Since exec is designed for unattended runs, the approval policy is usually set to never (no one is present to click approve). This means it is loose by default, so make sure to couple it with appropriate sandbox policies. Do not run exec blindly on critical projects in unisolated environments. Scripting and CI integrations for exec are covered in detail in the engineering chapters; for now, just know that "non-interactive runs are a separate path from TUI runs."

💡 Summary in one sentence: Interactive runs are "dining in" (monitoring, multi-turn chat), and exec runs are "takeout" (one-shot prompt and exit). Use the former for dialogue and the latter for automation/CI/batch runs—this is the CLI's killer feature.


08 Summary

This article has covered the codex command itself:

GoalHow to Do
Enter interactive TUIRun codex (include prompt to start working immediately)
Model / permission flags (on startup)--model / --sandbox / --ask-for-approval
Target working directory--cd <path> (no need to cd first)
Attach images-i <image-path>
Switch models / check status / view diffs mid-session/model / /status / /diff
Run shell commands quicklyPrefix prompt with !
Redraw TUI layoutCtrl+L (keeps conversation)
Write long promptsCtrl+G to open an external editor
One-shot run and exit (automation)codex exec "..."

You should now be able to: deconstruct any codex command into main command + subcommand + flags + prompt; navigate the TUI zones; use the eight high-frequency flags to start; run slash commands and keyboard shortcuts; and choose between interactive and exec runs.

Remember: the CLI is not a "watered-down Desktop App"; it is the most complete and automation-ready entry. Once you cross the terminal barrier, you will find it can do much more than a graphical interface.


The next article 09 · IDE Extensions (VS Code, etc.): now that we are comfortable with the CLI, we know most coding is done inside editors. The next article packs Codex into editors like VS Code and Cursor—chats in the sidebar, diffs in the editor panel... how to use the CLI's power without leaving your editor. Let's discuss it next.