Skip to the content.

The Art of Command Line for AI Coding Agents: Claude Code, Codex CLI, Gemini CLI and OpenCode on One Page

A one-page guide to working well with AI coding agents in the terminal: Claude Code, OpenAI Codex CLI, Gemini CLI and OpenCode. It covers installation, daily workflow, prompts that work, context and memory files (CLAUDE.md, AGENTS.md, GEMINI.md), permissions and sandboxing, headless mode for scripts and CI, parallel agents with git worktrees, MCP servers, hooks, cost control and safety. It is for developers who already live in the terminal and want terminal AI agents to make them faster without making their codebase or machine less safe.

Last reviewed: December 2026. Commands and flags below were checked against each tool’s official documentation at review time. These tools ship updates weekly, so run --help or /help when something does not match.


Contents


The Short Version

If you read nothing else:

  1. Commit before you start. A clean git status is your undo button.
  2. Ask for a plan first on anything bigger than a one-line fix. Read it, fix it, then let the agent build.
  3. Give the agent a way to check its own work: a test command, a type checker, a linter, a script that reproduces the bug.
  4. Write an instruction file (CLAUDE.md or AGENTS.md) with build, test and style commands. Keep it short.
  5. Keep context clean. Start a new session for a new task. Compact or clear when a session gets long.
  6. Never run with all safety off outside a container or VM. Approval prompts and sandboxes exist for good reasons.
  7. Review every diff as if a new teammate wrote it. You are responsible for what you merge.
  8. Treat anything the agent reads as untrusted: web pages, issues, dependencies and logs can contain instructions aimed at the agent.

Install and First Run

Pick one install method per tool. Each also has an IDE integration and other install options; see the linked docs.

Claude Code

# Native installer (macOS, Linux, WSL)
curl -fsSL https://claude.ai/install.sh | bash
# or Homebrew
brew install --cask claude-code
# or npm
npm install -g @anthropic-ai/claude-code

cd your-project
claude

Docs: Claude Code overview.

OpenAI Codex CLI

# Standalone installer (macOS, Linux)
curl -fsSL https://chatgpt.com/codex/install.sh | sh
# or npm
npm install -g @openai/codex
# or Homebrew
brew install --cask codex

cd your-project
codex

Docs: Codex CLI and the openai/codex repository.

Gemini CLI

# Try without installing
npx @google/gemini-cli
# or install globally
npm install -g @google/gemini-cli
# or Homebrew
brew install gemini-cli

cd your-project
gemini

Docs: Gemini CLI documentation and the google-gemini/gemini-cli repository.

OpenCode

# Installer script
curl -fsSL https://opencode.ai/v2/install | bash
# or npm
npm install -g @opencode/cli
# or Homebrew
brew install anomalyco/tap/opencode

cd your-project
opencode

Docs: OpenCode documentation and the anomalyco/opencode repository. OpenCode works with many model providers, including local models.

First run checklist: sign in or set an API key, run the agent inside a git repository, and start with a read-only question such as “Explain how this project is structured and how to run its tests.”


The Four Tools Side by Side

  Claude Code Codex CLI Gemini CLI OpenCode
Start interactive claude codex gemini opencode
One-shot, non-interactive claude -p "task" codex exec "task" gemini -p "task" opencode run "task"
Continue last session claude -c codex resume gemini --resume latest /sessions in the TUI
Project instruction file CLAUDE.md (can also use an existing AGENTS.md) AGENTS.md GEMINI.md AGENTS.md
Generate the instruction file /init /init /init see rules docs
Settings file .claude/settings.json, ~/.claude/settings.json ~/.codex/config.toml ~/.gemini/settings.json opencode.jsonc
Plan-only mode --permission-mode plan or Shift+Tab read-only sandbox (-s read-only) --approval-mode plan or /plan built-in plan agent
Add an MCP server claude mcp add ... codex mcp add ... gemini mcp add ... config file
Machine-readable output --output-format json or stream-json --json --output-format json or stream-json see CLI docs

Notes on the table:


The Core Loop: Explore, Plan, Build, Verify

The single biggest improvement for most people is to stop asking for code immediately.

1. Explore

Read the files involved in user signup (routes, service, database model, tests).
Don't change anything yet. Summarize how signup works and list anything surprising.

2. Plan

Plan how to add email verification to signup. Include: files to change,
new database fields, the migration, how tokens expire, and which tests to add.
Ask me about anything ambiguous before writing code.

Use a plan or read-only mode here so nothing is edited by accident. Read the plan. Edit it. This is where you catch wrong assumptions cheaply.

3. Build

Implement the plan. Work in small steps. After each step run `npm test -- signup`
and fix failures before moving on.

4. Verify

Run the full test suite, the type checker and the linter. Then show me `git diff --stat`
and summarize every change in one line per file.

5. Commit

Review the diff yourself, then commit (or ask the agent to write the commit message):

Write a conventional commit message for the staged changes. Don't commit; just print it.

Why it works: the agent spends tokens understanding before acting, you review a plan instead of 400 lines of code, and the agent has an objective “done” signal (tests pass).


Prompts That Work

Be specific about the goal, the constraints and the check

Weak Strong
“Fix the bug.” “Users get a 500 when the cart is empty. Reproduce it with a failing test in tests/cart.test.ts, then fix it. Don’t change the public API.”
“Add tests.” “Add tests for parseDate covering leap years, invalid input and time zones. Use the existing Vitest style in tests/utils.”
“Make it faster.” “The /search endpoint takes about 2s. Profile it, tell me the top three causes, and propose fixes before changing code.”
“Refactor this.” “Split OrderService into smaller services by responsibility. Keep behavior identical; all existing tests must still pass.”
“Update the docs.” “Update README.md install steps to match package.json scripts. Keep the existing tone and headings.”

Reusable prompt patterns

Reproduce first

Before fixing anything, write a test or script that reproduces this bug and show me it failing.

Ask clarifying questions

Ask me up to five questions about anything unclear before you start.

Constrain the blast radius

Only modify files under src/billing/. If you think another file needs changing, stop and tell me why.

Explain the diff

For each changed file, explain why the change was needed and what could break.

Second opinion

Review the uncommitted changes as a strict senior reviewer. List bugs, missing tests and risky assumptions. Don't fix anything.

Learn the codebase

I'm new to this repo. Give me a 10-minute tour: entry points, main modules, data flow, how to run and test, and the three files I should read first.

Point at files instead of pasting them

All four tools let you reference files directly in a prompt (for example with @path/to/file in Claude Code, Gemini CLI and OpenCode), and can read files themselves. Pasting huge files wastes context; pointing lets the agent read only what it needs.

Give it pictures

Screenshots of a broken layout, a design mockup or an error dialog are often clearer than words. Claude Code, Codex CLI (-i path/to/image.png) and Gemini CLI can take images as input in supported setups; check your OpenCode provider and model for image support.


Instruction Files: Teach the Agent Your Project Once

Instruction files are loaded at the start of every session. Write them once; every session benefits.

What to put in them

# Project guide for coding agents

## Commands
- Install: `pnpm install`
- Dev server: `pnpm dev`
- Test everything: `pnpm test`
- Test one file: `pnpm test -- path/to/file.test.ts`
- Type check: `pnpm typecheck`
- Lint and format: `pnpm lint --fix`

## Rules
- TypeScript strict mode; no `any`.
- New code needs tests next to it (`*.test.ts`).
- Database changes need a migration in `db/migrations/`.
- Never edit files in `generated/`; run `pnpm codegen` instead.

## Architecture
- `apps/web` Next.js front end, `apps/api` Fastify API, `packages/db` Drizzle schema.
- Business logic lives in `apps/api/src/services`; routes stay thin.

## Before you finish
- Run `pnpm typecheck && pnpm test` and fix failures.

Rules for good instruction files

Where each tool looks

Tool Global file Project file Notes
Claude Code ~/.claude/CLAUDE.md CLAUDE.md, CLAUDE.local.md Supports @path imports; subdirectory files load on demand (memory docs)
Codex CLI ~/.codex/AGENTS.md (or AGENTS.override.md) AGENTS.md from the repo root down to the current directory Override files allow temporary changes (AGENTS.md docs)
Gemini CLI ~/.gemini/GEMINI.md GEMINI.md Manage with /memory (GEMINI.md docs)
OpenCode global rules file AGENTS.md in each directory where it applies See rules docs

Managing Context

The context window is the agent’s working memory. When it fills with old logs, failed attempts and irrelevant files, quality drops.


Permissions, Approval Modes and Sandboxes

Every tool lets you choose how much the agent can do without asking. Pick the least permissive mode that keeps you productive.

Claude Code

Permission modes (docs): default (asks before edits and commands), acceptEdits (edits without asking), plan (read-only planning), auto, dontAsk and bypassPermissions. Cycle common modes with Shift+Tab or start with --permission-mode.

Fine-grained rules live in settings:

{
  "permissions": {
    "allow": ["Bash(npm test:*)", "Bash(git status)", "Bash(git diff:*)"],
    "deny": ["Read(./.env)", "Read(./secrets/**)", "Bash(git push:*)"]
  }
}

Put team rules in .claude/settings.json (committed) and personal ones in .claude/settings.local.json (not committed). Use /permissions to view and edit rules interactively. Claude Code also offers OS-level sandboxing for shell commands.

Codex CLI

Two separate controls (docs):

codex -s read-only                     # look but don't touch
codex -s workspace-write -a on-request # edit the repo, ask before anything else

codex exec runs in a read-only sandbox by default. The flag --dangerously-bypass-approvals-and-sandbox (alias --yolo) removes both protections; the docs say to use it only inside an externally hardened environment.

Gemini CLI

--approval-mode accepts default, auto_edit, yolo or plan (CLI reference). --sandbox (-s) runs tools in a sandboxed environment. Use /permissions and policies to control tool access.

OpenCode

Permissions are rules in opencode.jsonc with an action (such as shell or read), a resource pattern and an effect of allow, ask or deny (docs). For example, allow git status *, ask for everything else, and deny git push *. The built-in plan agent explores without editing normal project files.

A sensible default policy for any tool

Action Policy
Read files in the repo Allow
Run tests, linters, type checkers Allow
Edit files in the repo Allow, or ask while you are building trust
Install packages Ask
Network access, curl, ssh Ask
git push, deploy, publish, database migrations against real databases Deny for the agent; you do it
Read .env, keys, credentials Deny
Anything outside the project directory Ask or deny

Safety: The Rules That Prevent Disasters

  1. Work in a git repository with a clean tree. git stash, git diff and git restore undo most mistakes. Many agents also have their own checkpoints or undo, but git is the one you control.
  2. Never bypass all approvals on your main machine. If you want full autonomy, use a container, a VM or a disposable cloud dev environment with no production credentials.
  3. Keep secrets out of reach. Deny reads of .env and key files, use short-lived tokens, and never paste secrets into prompts.
  4. Beware the dangerous combination. An agent that can (a) read private data, (b) read untrusted content such as web pages, issues or emails, and (c) send data out (network, git push, comments) can be tricked into leaking data by instructions hidden in that content. Remove at least one of the three. Simon Willison’s write-up of the lethal trifecta explains the risk well.
  5. Review dependency additions. Agents sometimes add packages with similar names to real ones. Check every new dependency before installing it.
  6. Read before you run. If the agent suggests a command you do not understand, ask it to explain first.
  7. Don’t let agents push to protected branches or deploy. Make them open a pull request; humans merge.
  8. Log what happened. Keep transcripts or traces for anything run unattended, so you can audit it.

Headless Mode: Agents in Scripts, Pipes and CI

Every tool has a non-interactive mode, which makes agents composable with normal Unix tools.

One-liners

# Claude Code: explain a diff in plain English
git diff main | claude -p "Explain these changes for a release note. Bullet points, no code."

# Codex CLI: summarize risky areas, read-only by default
codex exec "Summarize the repository structure and list the top 5 risky areas"

# Gemini CLI: JSON output for scripts
gemini -p "List every TODO in src/ with file and line" --output-format json

# OpenCode
opencode run "Explain how authentication works in this repository"

Pipe data in, get structured data out

# Triage a log file with Claude Code and get JSON back
tail -n 500 app.log | claude -p "Group these errors by root cause. Return JSON: [{cause, count, example}]" --output-format json

# Limit an unattended run (Claude Code, print mode only)
claude -p "Fix the failing test in tests/date.test.ts" --max-turns 10 --allowedTools "Read,Edit,Bash(npm test:*)"

# Codex: let it edit the workspace, save only the final message
codex exec --sandbox workspace-write --output-last-message result.md "Update the CHANGELOG for the last 10 commits"

In CI

Good headless tasks

Task Why it suits headless mode
First-pass code review comments Read-only, human reviews the result
Changelog and release notes from commits Text in, text out
Lint-fix or type-fix on a branch Objective success check
Flaky test investigation report Read-only analysis
Translating docs or error messages Easy to verify by spot checks
Bulk refactors across many repos Scripted, but review each pull request

Parallel Agents with Git Worktrees and tmux

Running several agents at once is easy if each one has its own working directory. Git worktrees give you that without cloning again.

# Create two worktrees on new branches
git worktree add ../myapp-search -b feat/search
git worktree add ../myapp-billing -b fix/billing-rounding

# Run one agent in each (separate terminal panes or tmux windows)
cd ../myapp-search  && claude
cd ../myapp-billing && codex

# When done
git worktree list
git worktree remove ../myapp-search

Claude Code can also create a worktree for you with --worktree (-w), which places it under .claude/worktrees/.

A minimal tmux layout:

tmux new-session -d -s agents -c ../myapp-search
tmux split-window -h -t agents -c ../myapp-billing
tmux attach -t agents

Tips:


Connecting Tools with MCP

The Model Context Protocol (MCP) lets agents use external tools: issue trackers, databases, browsers, documentation search and more.

# Claude Code: a remote HTTP server, and a local stdio server
claude mcp add --transport http docs https://example.com/mcp
claude mcp add --transport stdio files -- npx -y @modelcontextprotocol/server-filesystem ./docs

# Codex CLI: stdio server (stored in ~/.codex/config.toml)
codex mcp add files -- npx -y @modelcontextprotocol/server-filesystem ./docs

# Gemini CLI
gemini mcp add files npx -y @modelcontextprotocol/server-filesystem ./docs

OpenCode configures MCP servers in its config file; see the OpenCode docs.

Replace https://example.com/mcp with a real server URL. Check status in a session with /mcp (Claude Code, Codex CLI, Gemini CLI).

MCP hygiene:


Hooks and Guardrails

Hooks run your own scripts at points in the agent’s lifecycle. They turn “please remember to” into “always happens”.

Claude Code example: block destructive shell commands before they run (hooks docs). In .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard.sh" }
        ]
      }
    ]
  }
}

.claude/hooks/guard.sh (make it executable with chmod +x):

#!/usr/bin/env bash
# Reads the tool call as JSON on stdin. Exit code 2 blocks the call and shows stderr to the agent.
cmd=$(jq -r '.tool_input.command // empty')
if printf '%s' "$cmd" | grep -Eq '(rm -rf /|git push --force|DROP TABLE)'; then
  echo "Blocked by project guard: $cmd" >&2
  exit 2
fi
exit 0

More hook ideas:

Event Hook Benefit
After a file edit Run the formatter on that file Consistent style without asking
Before a shell command Block dangerous patterns Safety net
When the agent finishes Run tests and report failures back The agent cannot “finish” with red tests
On notification Send a desktop notification You can step away while it works

Gemini CLI and Codex CLI also support hooks; see /hooks in Gemini CLI and the Codex configuration docs.


Shell Tools That Make Agents Better

Agents use your shell. Faster, clearer tools mean better results and less wasted context.

Tool Why agents benefit
ripgrep (rg) Fast code search that respects .gitignore
fd Simple, fast file finding
jq Slice JSON output instead of dumping it into context
GitHub CLI (gh) Read issues and pull requests, check CI, open pull requests
fzf For you: pick files and sessions quickly
direnv Per-project environment variables without global pollution

Also helpful: a Makefile or package.json scripts with obvious names (test, lint, typecheck, dev). Agents find and use them reliably, and so do new teammates.

Output tips:


Cost and Usage Control


Slash Command Cheat Sheet

Common in-session commands. Availability varies by version; type / to see the current list.

Purpose Claude Code Codex CLI Gemini CLI OpenCode
Help or command list /help type / /help type /
Create instruction file /init /init /init see rules docs
Clear or new conversation /clear /new /clear /new
Compress history /compact /compact /compress automatic compaction
Switch model /model /model /model /models
Permissions /permissions /permissions /permissions config file
MCP status /mcp /mcp /mcp config file
Resume a session /resume codex resume /resume /sessions
Undo or rewind /rewind git /rewind or /restore /undo
Usage and stats /usage or /context /status /stats in the TUI
Review changes ask, or a review skill /review, /diff ask ask
Memory and instructions /memory edit AGENTS.md /memory edit AGENTS.md

Keyboard habits worth learning in Claude Code: Shift+Tab cycles permission modes, Esc interrupts the current action so you can redirect it.


Troubleshooting

Symptom Likely cause Fix
Agent ignores your conventions Instruction file missing, too long or vague Add exact commands and checkable rules; trim the rest
Agent keeps “fixing” by editing tests No rule against it Say “Do not modify tests unless I ask” in the prompt and instruction file
Quality drops late in a session Context full of old attempts Save notes to a file, /clear, restart with a focused prompt
Agent loops on the same failing approach Missing information Stop it, give the actual error output, or ask for three alternative hypotheses
Huge, unfocused diffs Task too big Split into steps; ask for a plan; limit to a directory
Commands hang Interactive prompts (pagers, git editors, watch mode) Use non-interactive flags: --no-pager, CI=1, --run for test runners
MCP tool not available Server failed to start or auth expired Check /mcp; run the server command manually to see errors
Agent can’t find the test command Not documented Add it to the instruction file and package.json or Makefile
Different results between team members Personal settings differ Commit shared settings and instruction files; keep personal ones local

Anti-Patterns


Which Agent Should I Use?

They overlap heavily, and switching is cheap if you keep instructions in AGENTS.md. Things to compare on your own codebase:

Question What to test
Which models do you have access to and trust? Each tool works best with its own provider’s models; OpenCode supports many providers
How strict are your security needs? Sandboxing options, permission rules, enterprise settings, where data is sent
Do you need CI integration? Official GitHub Actions and headless flags
Do you want extensibility? Hooks, MCP, skills, plugins, sub-agents
What does it cost for your usage pattern? Plans versus pay-as-you-go; test with a week of real work

Run the same three real tasks from your backlog through two tools and compare diffs, time and cost. That beats any benchmark.

Other open-source terminal agents worth knowing: Aider, OpenHands, Qwen Code, and the VS Code-based Cline.


FAQ

What is a terminal AI coding agent? A program that runs in your terminal, reads your codebase, runs commands and edits files to complete tasks you describe in natural language, asking for approval according to rules you set.

Is it safe to let an AI agent run commands on my computer? It can be, with guardrails: approval prompts or sandboxes, denied access to secrets, a clean git tree, and no unattended pushes or deploys. Full autonomy belongs in a container or VM.

What is the difference between CLAUDE.md and AGENTS.md? Both are project instruction files loaded into the agent’s context. CLAUDE.md is Claude Code’s file; AGENTS.md is an open convention used by Codex CLI, OpenCode and many others. Many teams keep one source of truth and reference it from the other.

Can I use these agents with local models? OpenCode supports many providers, including local ones. Results with local models vary a lot on long, multi-step tasks.

How do I stop the agent from editing tests to make them pass? Say so explicitly in the prompt and the instruction file, deny edits to the tests directory for that task, and review diffs to test files with extra care.

Should I use these in CI? Yes for read-only or low-risk tasks (reviews, summaries, lint fixes on a branch) with minimal permissions. Be careful with untrusted inputs such as pull requests from forks.

How do I make the agent follow our code style? Automate it: formatter and linter commands in the instruction file, plus a hook or a finishing step that runs them.

Why does the agent get worse in long sessions? Its context fills with stale information and failed attempts. Compact or start fresh, and keep durable notes in files.


Where to Go Next


Contributing

Pull requests are welcome. Please keep entries accurate:

License

This guide is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). Product names belong to their owners; this guide is independent and not affiliated with any of the tools described.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.