Terminal · Claude Code · Codex · Command line

Terminal Mastery with Claude Code and Codex: Commands, Flags, Shortcuts and Scripts

Khairul Alam·October 2026·~30 min read
Claude CodeCodex CLITerminalCLI flagsScriptingShortcuts

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.

~/project — zsh $ git diff --staged | \ claude -p "commit message?" Add retry with backoff to the upload client $ codex exec --json "..." | jq Pipes are magic! Your shell + an agent
The terminal gives an agent the one thing a chat window cannot: your whole toolbox, glued together with pipes.
The whole guide in 60 seconds
  • 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+Tab modes and Esc Esc rewind (Claude Code).
  • Pipe text in, ask for --output-format json (Claude) or --json (Codex), and post-process with jq.
  • 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
  1. Four ways to run an agent
  2. Install, sign in, update, diagnose
  3. Starting a session
  4. Inside the session: input tricks and shortcuts
  5. Slash commands you will use daily
  6. The flags that matter
  7. Permissions and sandboxes from the terminal
  8. Scripting: pipes, JSON and CI
  9. Sessions: resume, fork, background
  10. Parallel work: worktrees and tmux
  11. Configuration and troubleshooting
  12. Make your terminal comfortable
  13. Aliases and shell recipes
  14. Cheat sheet and checklist

1. Four ways to run an agent

Interactiveclaudecodexyou chat, approve,steer One-shotclaude -pcodex execanswer, exit,scriptable Backgroundclaude --bgclaude agentsruns while youdo other things Cloudclaude --cloudcodex cloudruns on remotemachines More automation to the right, less hand-holding. Start on the left. Cloud and Remote Control need a signed-in account of the right plan.
Pick the mode by how much you want to watch. Most days: interactive for thinking, one-shot for chores.
ModeClaude CodeCodexUse it for
InteractiveclaudecodexExploring, planning, back-and-forth changes.
One-shotclaude -p "query"codex exec "query"Scripts, git hooks, CI, quick answers piped to other tools.
Backgroundclaude --bg "task", claude agentscodex agents, codex queueLong tasks while you keep working.
Cloudclaude --cloud "task"codex cloudTasks that should run on a remote machine and open a PR.

2. Install, sign in, update, diagnose

TaskClaude CodeCodex
Check versionclaude --versioncodex --version
Sign inclaude 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 outclaude auth logoutcodex logout
Updateclaude update, or claude install stable / latestcodex update (where supported)
Health checkclaude doctor (read-only, no session needed)codex doctor
Token for CIclaude 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 stateclaude purge ~/work/repo --dry-runcodex 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)

TypeWhat happens
/ at the startCommands 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 startShell mode: runs your command directly, adds its output to the session, and Claude responds to it. !git status, !npm test.
? on an empty lineShows the shortcut help panel.
Paste an imageCtrl+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

KeysAction
Shift+TabCycle permission modes: default, acceptEdits, plan, and others you have enabled.
EscStop the current response mid-turn. Claude keeps the work done so far, so you can redirect.
Esc EscWith text in the prompt: clear it (saved to history). With an empty prompt: open rewind.
Ctrl+CInterrupt a running operation. Press again on an empty prompt to exit.
Ctrl+DExit (press twice quickly).
Ctrl+RSearch your prompt history.
Ctrl+G or Ctrl+X Ctrl+EEdit the prompt in your $EDITOR. Best for long prompts.
Ctrl+OToggle the transcript viewer: tool calls, timestamps, the model used.
Ctrl+BSend a running command or agent to the background (tmux users press it twice).
Ctrl+TShow or hide the task checklist.
Ctrl+SStash the prompt you are writing; press again on an empty prompt to restore it.
Ctrl+LRedraw a garbled screen without losing history.
Ctrl+ZSuspend to the shell (Unix); fg brings it back.
Option+P / Alt+PSwitch model without clearing the prompt.
Option+T / Alt+TToggle extended thinking (not on models that always think).
Option+O / Alt+OToggle fast mode.
Ctrl+A Ctrl+E Ctrl+K Ctrl+U Ctrl+W Ctrl+YReadline-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

CommandWhat it does
/helpHelp and the list of commands.
/clearNew conversation, empty context. Use between unrelated tasks.
/compact [focus]Summarise the history to free context. Optionally say what to keep.
/contextColored 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.
/permissionsView and edit allow / ask / deny rules.
/diffReview 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-reviewLook 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, /forkResume, name, branch or copy a conversation.
/btw [question]Ask a side question without adding to the conversation.
/tasksSee 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.
/initCreate a CLAUDE.md for the project.
/memoryEdit CLAUDE.md files and auto-memory.
/mcp, /hooks, /skills, /plugin, /agentsManage extensions (see the agents article for subagents).
/add-dir, /cdAdd 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, /tuiSettings, status, checkup, look and feel (Section 12).

Codex CLI

CommandWhat it does
/new, /clearStart a fresh chat; /clear also clears the screen. /new name names the chat.
/compactSummarise to free context.
/modelChoose model and reasoning effort.
/permissionsSwitch between approval and sandbox presets.
/planPlan before changing anything.
/reviewReview local changes or a branch.
/diffShow the Git diff.
/mention pathAttach a file or folder to the prompt (like typing @).
/initCreate an AGENTS.md.
/statusModel, approvals, usage and other session state.
/resume, /fork, /sideReload a saved chat, branch one, or ask a quick side question in an ephemeral fork.
/goalGive a long task a goal to keep working toward.
/ps, /stopList background terminals and their output; stop them.
/mcp, /skills, /hooksExtensions.
/fastToggle a faster service tier, if the model has one.
/keymap, /debug-configCustomise keys; see which config layer won.
/exit, /quitLeave.

Which commands appear depends on version and plan, so type / to see yours.

6. The flags that matter

Claude Code

FlagWhat it does
-p, --printAnswer once and exit (non-interactive).
-c, --continueContinue 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, --nameName the session (shown in the picker and terminal title).
--modelAlias (sonnet, opus, haiku, fable) or a full model name.
--effortlow, medium, high, xhigh, max (depends on model).
--fallback-modelModels to try if the main one is overloaded, e.g. sonnet,haiku.
--permission-modedefault, acceptEdits, plan, auto, dontAsk, bypassPermissions.
--allowedTools / --disallowedToolsTools that run without asking / tools that are denied. Patterns like "Bash(git diff *)".
--toolsRestrict the built-in tool set, e.g. "Bash,Edit,Read".
--add-dirExtra folders Claude may read and edit.
-w, --worktree [name]Start in an isolated git worktree. --tmux adds a tmux session for it.
--bg, --backgroundStart 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-formattext, json, stream-json (with -p).
--json-schemaForce the final answer to match a JSON Schema (with -p).
--max-turns, --max-budget-usdStop after N turns or a spend estimate (with -p).
--bareSkip hooks, plugins, MCP discovery, auto-memory and CLAUDE.md discovery for a fast, predictable start (scripts).
--settings, --setting-sourcesLoad extra settings (file or inline JSON) / choose which settings layers load.
--mcp-config, --strict-mcp-configLoad MCP servers from a file / use only those.
--agents, --agentDefine subagents as JSON / run the session as an agent.
--debug[=filter], --debug-file, --verboseTroubleshooting output.
--safe-modeStart with all customisations off to find out which one breaks things.

Codex

FlagWhat it does
-m, --modelChoose the model.
-s, --sandboxread-only, workspace-write or danger-full-access.
-a, --ask-for-approvalon-request (model decides when to ask) or never.
--approve-for-meRoute 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, --cdWorking root.
--add-dirExtra writable folders.
--worktreeRun in a new managed git worktree.
-i, --imageAttach image(s) to the first prompt.
--searchAllow live web search.
-c key=valueOverride any config.toml value for this run, e.g. -c model="...".
-p, --profileLayer a named config file on top of your base config. (Note: -p means profile here, not print.)
--enable / --disableTurn a feature on or off for this run.
--oss, --local-providerUse a local open-source model provider (lmstudio or ollama).
--no-alt-screenInline mode that keeps your terminal scrollback.
--strict-configFail if config.toml has fields this version does not know.
codex exec: --json, -o, --output-schema, --ephemeral, --skip-git-repo-check, --colorJSON 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 CodeCodex
Read-only explorationclaude --permission-mode plancodex -s read-only
Normal work with promptsclaude (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
Before you use a “no checks” flag
  • 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

git difflogs, files | claude -pcodex execprompt + stdin | jqgrep, tee file stdin in, text or JSON out: the agent is one more Unix tool.
The agent reads standard input and writes standard output, so it composes like 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

9. Sessions: resume, fork, background

GoalClaude CodeCodex
Continue the latestclaude -ccodex resume --last
Pick from a listclaude -r or /resumecodex resume or /resume
Resume by name or IDclaude -r auth-refactorcodex resume <name-or-id>
Branch without losing the originalclaude -r <id> --fork-session, /branchcodex fork --last, /fork
Resume the session linked to a PRclaude --from-pr 123—
Name itclaude -n "name", /rename/new name
Hide / delete old sessionsclaude purgecodex archive, codex unarchive, codex delete
Apply a cloud result locallyclaude --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

feature/auth $ claude -w auth editing Login.kt... feature/ui $ claude -w ui editing Theme.kt... review $ codex review --base main
One worktree and one branch per agent keeps parallel edits from colliding.
# 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

11. Configuration and troubleshooting

Where settings come from

Claude CodeCodex
User config~/.claude/settings.json~/.codex/config.toml
Project config.claude/settings.json (shared), .claude/settings.local.json (yours).codex/config.toml
Instructions fileCLAUDE.mdAGENTS.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 shellShell environment; CODEX_HOME moves the config folder

When something is off

  1. Check the basics: claude doctor / codex doctor, then claude auth status / codex login status.
  2. Strip customisations: claude --safe-mode starts with CLAUDE.md, skills, plugins, hooks and MCP servers off. If the problem disappears, add things back one by one.
  3. Read the logs: claude --debug='mcp,startup' or --debug-file /tmp/claude.log. In Codex, /debug-config shows which config layer set a value.
  4. Check the layers: a project file can override your user file, and a managed policy overrides both.
  5. Garbled screen? Ctrl+L in Claude Code. In Codex try --no-alt-screen.
  6. 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

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 CodeCodex
Chat in this folderclaudecodex
Ask once, print, exitclaude -p "q"codex exec "q"
Pipe a diff ingit 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
Resumeclaude -c, claude -rcodex resume --last
Review changes/review, claude ultrareview 1234codex review --uncommitted
Parallel worktreeclaude -w namecodex --worktree
Backgroundclaude --bg "task"codex agents
Context too big/context, /compact, /clear/compact, /new
Cost/usage, --max-budget-usd/status
Diagnoseclaude doctor, --safe-modecodex doctor, /debug-config

Before you hand a task to an agent in the terminal

  1. Are you in the right folder and on the right branch (git status)?
  2. Is the trust level right: plan or read-only for exploring, narrow allow rules for editing, no bypass flags outside a sandbox?
  3. Is the work in a worktree if other things are in progress?
  4. For scripts: a turn cap, a budget cap, no prompts, and a human gate before merge?
  5. After the run: git diff, run the tests, and read the change yourself.
Mastery in one sentence

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.

← Back to all writing