Terminal · Claude Code · Codex · Command line
Terminal Mastery with Claude Code and Codex: Commands, Flags, Shortcuts and Scripts
Claude Code and Codex are at their best in a terminal, because a terminal is where your files, Git, tests and scripts already live. This guide takes you from typing claude or codex to running them in scripts, in the background, in parallel worktrees and in CI. It lists the commands, flags, slash commands and keyboard shortcuts that matter, with copy-ready recipes. Checked against Claude Code 2.1.308 and Codex CLI 0.160.0; run --help on your own version, because flags change quickly.
- Four ways to run an agent from the terminal: interactive (
claude,codex), one-shot (claude -p,codex exec), background (claude --bg), and cloud. - Inside a session, five prefixes do most of the work:
/commands,@files,!shell,Shift+Tabmodes andEsc Escrewind (Claude Code). - Pipe text in, ask for
--output-format json(Claude) or--json(Codex), and post-process withjq. - Control risk with a permission mode and a sandbox, not with politeness:
--permission-mode plan,-s read-only,--allowedTools. - Resume with
claude -c/codex resume --last. Run parallel work in worktrees (claude -w,codex --worktree). - Put your habits into shell aliases and small functions, and put team rules into CLAUDE.md / AGENTS.md.
Contents
- Four ways to run an agent
- Install, sign in, update, diagnose
- Starting a session
- Inside the session: input tricks and shortcuts
- Slash commands you will use daily
- The flags that matter
- Permissions and sandboxes from the terminal
- Scripting: pipes, JSON and CI
- Sessions: resume, fork, background
- Parallel work: worktrees and tmux
- Configuration and troubleshooting
- Make your terminal comfortable
- Aliases and shell recipes
- Cheat sheet and checklist
1. Four ways to run an agent
| Mode | Claude Code | Codex | Use it for |
|---|---|---|---|
| Interactive | claude | codex | Exploring, planning, back-and-forth changes. |
| One-shot | claude -p "query" | codex exec "query" | Scripts, git hooks, CI, quick answers piped to other tools. |
| Background | claude --bg "task", claude agents | codex agents, codex queue | Long tasks while you keep working. |
| Cloud | claude --cloud "task" | codex cloud | Tasks that should run on a remote machine and open a PR. |
2. Install, sign in, update, diagnose
| Task | Claude Code | Codex |
|---|---|---|
| Check version | claude --version | codex --version |
| Sign in | claude auth login (add --console for API billing, --sso for SSO) | codex login |
| Who am I? | claude auth status (JSON; --text for people) | codex login status |
| Sign out | claude auth logout | codex logout |
| Update | claude update, or claude install stable / latest | codex update (where supported) |
| Health check | claude doctor (read-only, no session needed) | codex doctor |
| Token for CI | claude setup-token (long-lived OAuth token, printed once) | Use an API key in the CI secret store. |
| Shell completion | — | codex completion zsh (also bash, fish, powershell, elvish) |
| Wipe local state | claude purge ~/work/repo --dry-run | codex delete <session> |
3. Starting a session
# Claude Code
claude # interactive, in the current folder
claude "explain this project" # interactive, with a first prompt
claude -c # continue the latest conversation here
claude -r "auth-refactor" # resume by name or ID (no name: picker)
claude -n "my-feature" # give the session a name
claude --permission-mode plan # start in read-only plan mode
claude -w feature-auth # work in an isolated git worktree
# Codex
codex # interactive
codex "fix the failing tests" # interactive, with a first prompt
codex resume --last # continue the most recent session
codex resume <name-or-id> # resume a specific one (no id: picker)
codex -C ../other-repo # use another folder as the working root
codex --worktree # new managed git worktree for the session
Run these from the project root. The agent sees the folder you start in, and project files such as CLAUDE.md or AGENTS.md are read from there. To give access to a sibling folder add --add-dir ../lib (both tools have it).
4. Inside the session: input tricks and shortcuts
The five prefixes (Claude Code)
| Type | What happens |
|---|---|
/ at the start | Commands and skills. Type / to see the menu, then letters to filter. |
@ | File path autocomplete. @src/auth/Login.kt puts that file in the prompt. |
! at the start | Shell mode: runs your command directly, adds its output to the session, and Claude responds to it. !git status, !npm test. |
? on an empty line | Shows the shortcut help panel. |
| Paste an image | Ctrl+V (or Cmd+V in iTerm2, Alt+V on Windows) inserts an [Image #N] chip you can refer to by number. |
In Codex, type @ to mention a file or use /mention src/lib/api.ts, and attach images at launch with -i shot.png.
Claude Code keyboard shortcuts
| Keys | Action |
|---|---|
Shift+Tab | Cycle permission modes: default, acceptEdits, plan, and others you have enabled. |
Esc | Stop the current response mid-turn. Claude keeps the work done so far, so you can redirect. |
Esc Esc | With text in the prompt: clear it (saved to history). With an empty prompt: open rewind. |
Ctrl+C | Interrupt a running operation. Press again on an empty prompt to exit. |
Ctrl+D | Exit (press twice quickly). |
Ctrl+R | Search your prompt history. |
Ctrl+G or Ctrl+X Ctrl+E | Edit the prompt in your $EDITOR. Best for long prompts. |
Ctrl+O | Toggle the transcript viewer: tool calls, timestamps, the model used. |
Ctrl+B | Send a running command or agent to the background (tmux users press it twice). |
Ctrl+T | Show or hide the task checklist. |
Ctrl+S | Stash the prompt you are writing; press again on an empty prompt to restore it. |
Ctrl+L | Redraw a garbled screen without losing history. |
Ctrl+Z | Suspend to the shell (Unix); fg brings it back. |
Option+P / Alt+P | Switch model without clearing the prompt. |
Option+T / Alt+T | Toggle extended thinking (not on models that always think). |
Option+O / Alt+O | Toggle fast mode. |
Ctrl+A Ctrl+E Ctrl+K Ctrl+U Ctrl+W Ctrl+Y | Readline-style editing: line start, line end, cut to end, cut to start, cut word, paste. |
macOS: the Option/Alt shortcuts need your terminal to send Option as Meta. In Terminal.app and iTerm2 this is a profile setting; run /terminal-setup or check the terminal-config docs. Messages while it works: you can keep typing while Claude is busy. Your message is queued and sent after the current step.
For Codex, the interrupt and other keys are configurable. Run /keymap inside the CLI to see and change them, and /debug-config to see which config layer set a value.
5. Slash commands you will use daily
Claude Code
| Command | What it does |
|---|---|
/help | Help and the list of commands. |
/clear | New conversation, empty context. Use between unrelated tasks. |
/compact [focus] | Summarise the history to free context. Optionally say what to keep. |
/context | Colored grid of what fills your context window. |
/usage (alias /cost) | Session cost, plan limits and activity. |
/model [name] | Switch model; saved as your default for new sessions. |
/effort [level] | Set reasoning effort from low to max. |
/fast [on|off] | Toggle fast mode. |
/plan [task] | Enter plan mode, optionally starting on a task. |
/permissions | View and edit allow / ask / deny rules. |
/diff | Review the working-tree changes, including Claude’s edits. |
/review (alias of /code-review) | Review the current diff or a PR; flags like --fix and --comment exist. |
/security-review | Look for vulnerabilities in the changes on your branch. |
/rewind (/undo, /checkpoint) | Go back to an earlier point in the conversation and/or the code. |
/resume [session], /rename, /branch, /fork | Resume, name, branch or copy a conversation. |
/btw [question] | Ask a side question without adding to the conversation. |
/tasks | See and manage background work and subagents. |
/background [prompt] | Detach this session to run as a background agent. |
/loop [interval] [prompt] | Repeat a prompt while the session stays open. |
/goal [condition] | Keep working across turns until a condition is met. |
/init | Create a CLAUDE.md for the project. |
/memory | Edit CLAUDE.md files and auto-memory. |
/mcp, /hooks, /skills, /plugin, /agents | Manage extensions (see the agents article for subagents). |
/add-dir, /cd | Add a folder to the session, or move the session to another folder. |
/export [file], /copy [N] | Save the conversation as text, or copy the last reply (or the Nth latest). |
/config, /status, /doctor, /theme, /terminal-setup, /statusline, /keybindings, /tui | Settings, status, checkup, look and feel (Section 12). |
Codex CLI
| Command | What it does |
|---|---|
/new, /clear | Start a fresh chat; /clear also clears the screen. /new name names the chat. |
/compact | Summarise to free context. |
/model | Choose model and reasoning effort. |
/permissions | Switch between approval and sandbox presets. |
/plan | Plan before changing anything. |
/review | Review local changes or a branch. |
/diff | Show the Git diff. |
/mention path | Attach a file or folder to the prompt (like typing @). |
/init | Create an AGENTS.md. |
/status | Model, approvals, usage and other session state. |
/resume, /fork, /side | Reload a saved chat, branch one, or ask a quick side question in an ephemeral fork. |
/goal | Give a long task a goal to keep working toward. |
/ps, /stop | List background terminals and their output; stop them. |
/mcp, /skills, /hooks | Extensions. |
/fast | Toggle a faster service tier, if the model has one. |
/keymap, /debug-config | Customise keys; see which config layer won. |
/exit, /quit | Leave. |
Which commands appear depends on version and plan, so type / to see yours.
6. The flags that matter
Claude Code
| Flag | What it does |
|---|---|
-p, --print | Answer once and exit (non-interactive). |
-c, --continue | Continue the latest conversation in this folder. |
-r, --resume [id|name] | Resume a session, or open the picker. Add --fork-session to branch instead of reusing the ID. |
-n, --name | Name the session (shown in the picker and terminal title). |
--model | Alias (sonnet, opus, haiku, fable) or a full model name. |
--effort | low, medium, high, xhigh, max (depends on model). |
--fallback-model | Models to try if the main one is overloaded, e.g. sonnet,haiku. |
--permission-mode | default, acceptEdits, plan, auto, dontAsk, bypassPermissions. |
--allowedTools / --disallowedTools | Tools that run without asking / tools that are denied. Patterns like "Bash(git diff *)". |
--tools | Restrict the built-in tool set, e.g. "Bash,Edit,Read". |
--add-dir | Extra folders Claude may read and edit. |
-w, --worktree [name] | Start in an isolated git worktree. --tmux adds a tmux session for it. |
--bg, --background | Start as a background agent and return at once. |
--append-system-prompt[-file] | Add instructions to the default system prompt. --system-prompt[-file] replaces it. |
--output-format | text, json, stream-json (with -p). |
--json-schema | Force the final answer to match a JSON Schema (with -p). |
--max-turns, --max-budget-usd | Stop after N turns or a spend estimate (with -p). |
--bare | Skip hooks, plugins, MCP discovery, auto-memory and CLAUDE.md discovery for a fast, predictable start (scripts). |
--settings, --setting-sources | Load extra settings (file or inline JSON) / choose which settings layers load. |
--mcp-config, --strict-mcp-config | Load MCP servers from a file / use only those. |
--agents, --agent | Define subagents as JSON / run the session as an agent. |
--debug[=filter], --debug-file, --verbose | Troubleshooting output. |
--safe-mode | Start with all customisations off to find out which one breaks things. |
Codex
| Flag | What it does |
|---|---|
-m, --model | Choose the model. |
-s, --sandbox | read-only, workspace-write or danger-full-access. |
-a, --ask-for-approval | on-request (model decides when to ask) or never. |
--approve-for-me | Route approvals through automatic review, in the workspace-write sandbox. |
--dangerously-bypass-approvals-and-sandbox (--yolo) | No prompts, no sandbox. Only inside an already isolated environment. |
-C, --cd | Working root. |
--add-dir | Extra writable folders. |
--worktree | Run in a new managed git worktree. |
-i, --image | Attach image(s) to the first prompt. |
--search | Allow live web search. |
-c key=value | Override any config.toml value for this run, e.g. -c model="...". |
-p, --profile | Layer a named config file on top of your base config. (Note: -p means profile here, not print.) |
--enable / --disable | Turn a feature on or off for this run. |
--oss, --local-provider | Use a local open-source model provider (lmstudio or ollama). |
--no-alt-screen | Inline mode that keeps your terminal scrollback. |
--strict-config | Fail if config.toml has fields this version does not know. |
codex exec: --json, -o, --output-schema, --ephemeral, --skip-git-repo-check, --color | JSON event stream / write the last message to a file / force a JSON shape / do not save the session / allow running outside Git / color control. |
7. Permissions and sandboxes from the terminal
The terminal makes it easy to run an agent with the keys to your machine. Decide the trust level on purpose.
| You want… | Claude Code | Codex |
|---|---|---|
| Read-only exploration | claude --permission-mode plan | codex -s read-only |
| Normal work with prompts | claude (default mode) | codex (default preset; switch with /permissions) |
| Auto-accept file edits | --permission-mode acceptEdits | -s workspace-write -a on-request |
| Fewer prompts, safely | --permission-mode auto, or allow specific commands: --allowedTools "Bash(npm test)" | --approve-for-me |
| Allow only named tools in a script | --tools "Read,Grep", --permission-prompts none (denies instead of asking) | -s read-only -a never |
| No checks at all | --dangerously-skip-permissions | --yolo |
- Do it only in a throwaway container or VM with no internet and no secrets.
- An agent that reads untrusted text (web pages, issues, logs) can be tricked into running commands. Fewer prompts means fewer chances to notice.
- Prefer narrow allow rules, such as
"Bash(git diff *)", over blanket bypass.
Test a sandbox without the agent: codex sandbox runs a command inside a Codex-provided sandbox, so you can see what it blocks.
8. Scripting: pipes, JSON and CI
grep or sort.Claude Code one-shot recipes
# 1. Pipe content in
git diff --staged | claude -p "Write a one-line commit message"
cat error.log | claude -p "What is the root cause? Be brief."
# 2. Machine-readable result
claude -p "List the TODOs in src/" --output-format json | jq -r '.result'
# 3. Validated structure (the answer must match the schema)
claude -p "Summarise this repo" \
--json-schema '{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}'
# 4. Guard rails for unattended use
claude -p "Fix the failing test" \
--max-turns 8 --max-budget-usd 2 \
--allowedTools "Read" "Edit" "Bash(npm test)" \
--permission-mode acceptEdits
# 5. Fast, predictable start in CI (skips hooks, plugins, CLAUDE.md discovery)
claude --bare -p "Check for type errors in src/" \
--append-system-prompt-file ./ci-rules.txt
# 6. Continue a previous run
claude -c -p "Now also update the tests"
The JSON output includes the final text in a result field along with session and cost details. stream-json emits events as they happen (it needs --verbose with -p), which suits live dashboards. --no-session-persistence avoids saving the run to disk.
Codex one-shot recipes
# 1. Run a task and exit
codex exec "Add input validation to the signup form"
# 2. Pipe content in (stdin is appended to your prompt)
git diff | codex exec "Summarise this change for a PR description"
# 3. Events as JSON lines, and the final answer to a file
codex exec --json "Find unused dependencies" | jq -c 'select(.type)'
codex exec -o answer.txt "Summarise the architecture"
# 4. A required answer shape
codex exec --output-schema ./schema.json "List modules and owners"
# 5. Read-only, no saved session, outside a git repo
codex exec -s read-only --ephemeral --skip-git-repo-check "Explain this folder"
# 6. Review without opening the UI
codex review --uncommitted # staged, unstaged and untracked changes
codex review --base main # against a base branch
codex review --commit <sha> # one commit
codex review "Focus on security" # custom instructions
# 7. Continue or fork a non-interactive session
codex exec resume --last "Now add tests"
If stdin is piped and a prompt is given, Codex appends stdin as a block after the prompt. With no prompt (or -), the whole prompt is read from stdin.
Loops and batches
# Review every changed file, one call each
git diff --name-only main | while read f; do
claude -p "Review $f for bugs. Reply with 'OK' if none." --allowedTools "Read" < /dev/null
done
# Parallel fan-out, four at a time
ls src/*.kt | xargs -P4 -I{} sh -c 'claude -p "Add KDoc to {}" --permission-mode acceptEdits --max-turns 5'
Parallel writers on different files are fine; on the same file they clash (see parallel vs serial). Cap the budget and turns on every unattended call. Each call has its own cost, so a loop over 500 files is 500 requests.
CI and git hooks
- Authenticate with a secret:
claude setup-tokenoutput or an API key for Claude, an API key for Codex. Never print it into logs. - Make it deterministic:
--barefor Claude,--ignore-user-configand--ephemeralfor Codex. - No questions in CI: deny instead of ask (
--permission-prompts nonefor Claude,-a neverfor Codex). - Gate on exit code, and keep a human approval before merging anything the agent wrote.
- Pre-commit example:
git diff --staged | claude -p "Any secrets or debug prints? Answer NONE if clean."and fail the hook if the answer is notNONE. Keep such hooks fast and optional.
9. Sessions: resume, fork, background
| Goal | Claude Code | Codex |
|---|---|---|
| Continue the latest | claude -c | codex resume --last |
| Pick from a list | claude -r or /resume | codex resume or /resume |
| Resume by name or ID | claude -r auth-refactor | codex resume <name-or-id> |
| Branch without losing the original | claude -r <id> --fork-session, /branch | codex fork --last, /fork |
| Resume the session linked to a PR | claude --from-pr 123 | — |
| Name it | claude -n "name", /rename | /new name |
| Hide / delete old sessions | claude purge | codex archive, codex unarchive, codex delete |
| Apply a cloud result locally | claude --teleport (pull a cloud session here) | codex apply (latest diff), codex cloud |
Background sessions (Claude Code)
A background session keeps working after you close the terminal tab. A small supervisor process hosts them.
claude --bg "investigate the flaky checkout test" # prints a session ID, returns at once
claude agents # live view of all background sessions
claude agents --json # the same, for scripts
claude attach 7c5dcf5d # reconnect to it in this terminal
claude logs 7c5dcf5d # print recent output without attaching
claude stop 7c5dcf5d # stop it (transcript and worktree are kept)
claude respawn 7c5dcf5d # restart with the conversation intact
claude rm 7c5dcf5d # remove it from the list
claude daemon status # is the supervisor healthy?
Inside a running session, /background detaches it, and Ctrl+B pushes a single long command into the background. For Codex, codex agents browses agent sessions on the shared local server, and codex queue sends a message to an existing session.
10. Parallel work: worktrees and tmux
# Claude Code
claude -w feature-auth # worktree at .claude/worktrees/feature-auth
claude -w feature-auth --tmux # ...and open it in its own tmux session
claude -w "#123" # worktree branched from a pull request
# Codex
codex --worktree # managed git worktree for this session
# By hand (works for any tool)
git worktree add ../app-auth -b feature/auth
cd ../app-auth && claude
- tmux layout: one window, one pane per agent, plus a pane for
git status.tmux new -s agents,Ctrl+b %to split. - Claude agent teams can place each teammate in a tmux or iTerm2 pane:
claude --teammate-mode auto(see the agents article). - Clean up:
git worktree listthengit worktree remove ../app-authonce merged.
11. Configuration and troubleshooting
Where settings come from
| Claude Code | Codex | |
|---|---|---|
| User config | ~/.claude/settings.json | ~/.codex/config.toml |
| Project config | .claude/settings.json (shared), .claude/settings.local.json (yours) | .codex/config.toml |
| Instructions file | CLAUDE.md | AGENTS.md |
| Override for one run | --settings ./file.json or inline JSON | -c key=value, -p profile |
| Choose layers | --setting-sources user,project | --ignore-user-config, --strict-config |
| Environment variables | "env" block in settings or your shell | Shell environment; CODEX_HOME moves the config folder |
When something is off
- Check the basics:
claude doctor/codex doctor, thenclaude auth status/codex login status. - Strip customisations:
claude --safe-modestarts with CLAUDE.md, skills, plugins, hooks and MCP servers off. If the problem disappears, add things back one by one. - Read the logs:
claude --debug='mcp,startup'or--debug-file /tmp/claude.log. In Codex,/debug-configshows which config layer set a value. - Check the layers: a project file can override your user file, and a managed policy overrides both.
- Garbled screen?
Ctrl+Lin Claude Code. In Codex try--no-alt-screen. - Reinstall cleanly:
claude install stable, or reinstall Codex with your package manager.
MCP and plugins from the shell
claude mcp # manage MCP servers (add, list, remove...)
claude mcp login sentry # run a server's OAuth flow without the interactive panel
claude plugin install code-review@claude-plugins-official
codex mcp add / list / get / remove / login / logout
codex plugin add / list / remove
codex features list # inspect feature flags
12. Make your terminal comfortable
- Shift+Enter for a new line: run
/terminal-setupin Claude Code to install the keybinding in VS Code, Cursor, Alacritty or Zed. In Apple Terminal enable Option+Enter. Everywhere, a trailing\then Enter also adds a line. - Option as Meta (macOS): required for the
Alt+shortcuts. It is a profile setting in Terminal.app and iTerm2. - Long prompts:
Ctrl+Gopens your$EDITOR. SetEDITORin your shell profile. - Vim keys in the prompt:
/configthen Editor mode. The prompt then supports NORMAL and INSERT modes, motions such asw,b,0,$, and edits such asdd,cw,yy,p. - Look and feel:
/theme(including an auto light/dark option and colorblind-friendly themes),/statuslineto show model, branch or cost in the footer,/colorto tag a session. - Flicker-free fullscreen:
/tui fullscreenswitches the renderer and keeps your conversation./tui defaultgoes back. - Scrollback: for Codex
--no-alt-screenkeeps your terminal history; in Claude Code’s transcript view (Ctrl+O) you can search and open it in your editor. - Accessibility:
claude --ax-screen-readergives plain, flat output for screen readers. - Custom keys:
/keybindings(Claude Code) or/keymap(Codex).
13. Aliases and shell recipes
Put these in ~/.zshrc or ~/.bashrc. They are examples; change the names and flags to taste.
# short names
alias cc='claude'
alias ccc='claude -c' # continue
alias ccp='claude --permission-mode plan' # safe exploration
alias cx='codex'
alias cxr='codex resume --last'
# ask a question about the code, read-only, answer on stdout
ask() { claude -p "$*" --permission-mode plan; }
# commit message from the staged diff
cmsg() { git diff --staged | claude -p "Write a concise conventional commit message. Output only the message."; }
# explain the last failing command's output
why() { "$@" 2>&1 | tail -50 | claude -p "Why did this fail? Give the likely cause and the fix."; }
# review my branch against main with Codex
rv() { codex review --base "${1:-main}"; }
# new worktree + agent in one go
wt() { git worktree add "../$(basename "$PWD")-$1" -b "feature/$1" && cd "../$(basename "$PWD")-$1" && claude; }
Do not alias plain claude to include --dangerously-skip-permissions. It turns every session, including ones in untrusted folders, into a no-checks session.
14. Cheat sheet and checklist
| I want to… | Claude Code | Codex |
|---|---|---|
| Chat in this folder | claude | codex |
| Ask once, print, exit | claude -p "q" | codex exec "q" |
| Pipe a diff in | git diff | claude -p "q" | git diff | codex exec "q" |
| JSON out | --output-format json | --json, -o file |
| Plan only | --permission-mode plan, /plan | -s read-only, /plan |
| Resume | claude -c, claude -r | codex resume --last |
| Review changes | /review, claude ultrareview 1234 | codex review --uncommitted |
| Parallel worktree | claude -w name | codex --worktree |
| Background | claude --bg "task" | codex agents |
| Context too big | /context, /compact, /clear | /compact, /new |
| Cost | /usage, --max-budget-usd | /status |
| Diagnose | claude doctor, --safe-mode | codex doctor, /debug-config |
Before you hand a task to an agent in the terminal
- Are you in the right folder and on the right branch (
git status)? - Is the trust level right: plan or read-only for exploring, narrow allow rules for editing, no bypass flags outside a sandbox?
- Is the work in a worktree if other things are in progress?
- For scripts: a turn cap, a budget cap, no prompts, and a human gate before merge?
- After the run:
git diff, run the tests, and read the change yourself.
Treat the agent as a Unix tool with a brain: give it clear input (pipes, @ files), clear limits (modes, sandboxes, caps), and clear output (JSON, files, exit codes), and keep your own judgment at the end of the pipe.