Getting Started with Gemini CLI: From Zero to Productive in 30 Minutes
A hands-on beginner tutorial for Gemini CLI. Learn the essential commands, workflows, and patterns to become productive in your first 30 minutes.
Zhihao MuIntroduction
Most developer tools promise to save you time. Gemini CLI actually delivers on that promise — but only once you get past the initial "what do I even type?" phase that trips up almost every newcomer.
Gemini CLI is a terminal-based AI assistant that understands your codebase, operates on your local files, and integrates naturally into the workflows you already use. It is not a chatbot you open in a browser tab. It lives in your terminal, next to git, npm, and every other tool you run dozens of times a day. That proximity is what makes it genuinely useful.
The challenge is that the tool's surface area is large. There are flags, modes, pipe patterns, file operations, code generation shortcuts, and an MCP extension system that could occupy weeks of exploration. When you first install it, none of that is obvious, and the official documentation assumes more context than a first-timer has.
This guide takes a different approach: thirty minutes, twelve tasks, real code. By the time you finish reading — and more importantly, by the time you follow along at your own terminal — you will have used Gemini CLI to analyse a file, explain and generate code, review a function for bugs, batch-process files, and build a small end-to-end workflow. That breadth of hands-on experience is what separates someone who installed the tool from someone who actually uses it every day.
TL;DR
- Install with
npm install -g @google/gemini-cli(Node 18+ required) and authenticate in under two minutes. - Use
gemini "your question"for one-off queries; drop into interactive mode withgeminialone. - Pipe any file or command output directly into Gemini CLI for instant analysis.
- Code generation, test writing, bug finding, and file operations all follow the same simple pattern.
- Five core patterns cover eighty percent of daily use; master those before exploring advanced features.
Minute 0–5: Installation and First Run
Installing Gemini CLI
Open your terminal and run a single command:
npm install -g @google/gemini-cli
That's it. Gemini CLI has no native binaries, no Homebrew formula to pin, and no Docker image to pull. As long as you are running Node 18 or later, the install completes in thirty seconds or less. Verify it worked:
gemini --version
You should see a version string like 1.x.x. If you see command not found, your global npm bin directory is not on your PATH. The fastest fix:
export PATH="$(npm bin -g):$PATH"
Add that line to your ~/.zshrc or ~/.bashrc so it persists across sessions.
Authentication
Gemini CLI needs a Google API key to talk to the Gemini model. On first run, the CLI will open your browser automatically and walk you through Google's OAuth flow. If you prefer to skip the browser prompt and supply a key directly:
export GEMINI_API_KEY="your-key-here"
You can obtain a free API key from Google AI Studio in about two minutes. The free tier is generous enough for learning and moderate daily use.
Your First Command
With authentication complete, run:
gemini "Hello! What can you help me with today?"
The response will appear directly in your terminal, formatted with Markdown rendered as plain text. You are talking to Gemini 2.5 Pro (the default model as of 2026) from your shell prompt.
Understanding the Output
Gemini CLI renders responses with a few visual conventions worth recognising:
- Code blocks appear with syntax highlighting when your terminal supports colour.
- Inline code is wrapped in backticks and highlighted differently from prose.
- Lists and headings are rendered as-is — Markdown syntax is stripped and replaced with readable formatting.
- The cost counter (tokens used) appears at the bottom of each response if you run with
--verbose.
Run the same greeting again with the verbose flag to see the token breakdown:
gemini --verbose "Hello! What can you help me with today?"
That bottom line — Tokens: 42 in / 187 out — is your first signal about how efficiently you are prompting. Shorter, precise prompts produce faster, cheaper answers.
Minute 5–10: Your First Real Task
Analysing a File
Navigate to any project directory on your machine. If you do not have one handy, create a quick sample:
mkdir gemini-demo && cd gemini-demo
cat > utils.js << 'EOF'
function parseDate(input) {
const d = new Date(input);
if (isNaN(d)) return null;
return d.toISOString().split('T')[0];
}
function slugify(text) {
return text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
}
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
EOF
Now ask Gemini CLI to explain the file:
gemini "Explain what each function in utils.js does and whether there are any obvious issues."
Gemini CLI automatically reads files in your current working directory when you reference them by name. It will return a clear, function-by-function breakdown. No need to copy-paste the source into the prompt.
Targeting a Specific Function
You can be more surgical. Ask about one function only:
gemini "Look at the parseDate function in utils.js. What edge cases does it not handle?"
Expected response: the function does not handle null or undefined inputs, does not distinguish between genuinely invalid dates and dates outside a useful range, and silently returns null rather than throwing — which makes caller bugs silent. Those are real issues worth knowing before you ship the file.
Asking for a Summary
If you have landed in an unfamiliar codebase, a high-level summary is often the most valuable first step:
gemini "Give me a one-paragraph summary of what this project does based on the files in the current directory."
Gemini CLI will scan the directory, read the files it considers most informative (typically package.json, README.md, entry-point files), and produce a short summary. This works even on repositories with hundreds of files — the model prioritises intelligently rather than reading everything blindly.
Minute 10–15: Code Generation
Generating a Function
You have utils.js open in your editor. You need a function that validates an email address. Instead of searching StackOverflow:
gemini "Add a validateEmail function to utils.js. It should return true for valid email addresses and false otherwise. Use a regex that handles common edge cases."
Gemini CLI will write the function, explain its regex briefly, and note any caveats (for example, that no regex perfectly matches the RFC 5321 specification). The output is ready to paste directly into your file.
If you want Gemini CLI to write the change directly rather than just showing you:
gemini --write "Add a validateEmail function to utils.js."
The --write flag (also available as -w) instructs Gemini CLI to apply file edits automatically. It will always show you a diff first and ask for confirmation before touching your files.
Generating Tests
Test writing is one of the highest-value use cases because it is tedious and many developers skip it under deadline pressure. Gemini CLI removes the tedium:
gemini "Write a Jest test file for utils.js. Cover normal cases, edge cases, and invalid inputs for every function."
The output will include a complete utils.test.js file with describe/it blocks, meaningful test names, and assertions covering the edge cases the model already identified in the earlier analysis. Copy it into your project and run:
npx jest utils.test.js
If any tests fail, paste the error back:
npx jest utils.test.js 2>&1 | gemini "These test failures appeared after running utils.test.js against utils.js. Diagnose and fix."
This pipe pattern — feed command output into Gemini CLI — is one you will use constantly. More on that in the next section.
Generating Boilerplate
Gemini CLI handles boilerplate generation well because boilerplate is high-volume, low-creativity work. Generate an Express route handler:
gemini "Generate an Express.js route handler for POST /api/users that validates the request body, creates a user in a mock in-memory store, and returns the created user with a 201 status. Include proper error handling."
The output includes input validation, the success path, a 400 branch for bad input, and a 500 branch for unexpected errors. That is four concerns handled in ten seconds.
Minute 15–20: Code Review and Debugging
Piping Code for Review
The Unix pipe is one of the most powerful ways to use Gemini CLI. Feed any file directly into the model:
cat utils.js | gemini "Review this code for quality, security, and performance issues."
Or use input redirection, which is equivalent and slightly cleaner:
gemini "Review this code for quality, security, and performance issues." < utils.js
Both forms work identically. The content of utils.js becomes the context for the question.
Finding Bugs
Bug hunting via pipe is particularly effective because you can combine a diff with a question:
git diff HEAD~1 | gemini "I introduced a regression somewhere in this diff. What is most likely broken and why?"
Gemini CLI will read the changed lines and reason about side-effects that the diff might have introduced — missing null checks, changed function signatures that callers depend on, logic inversions, and similar patterns.
For a targeted bug hunt, describe the symptom:
cat utils.js | gemini "The slugify function is producing incorrect output when the input contains consecutive spaces. Identify the bug and suggest a fix."
The answer: replace(/\s+/g, '-') handles consecutive spaces correctly by treating them as a single group, but replace(/[^\w-]/g, '') runs second and silently removes characters rather than replacing them — which can produce double hyphens or leading/trailing hyphens in certain inputs. The model will catch that and suggest a corrected version.
Reviewing a Pull Request Locally
If you use GitHub and have the gh CLI installed, you can review a pull request entirely from the terminal:
gh pr diff 42 | gemini "Review this pull request. Focus on correctness, error handling, and anything that could cause issues in production."
This is the kind of workflow that genuinely saves time: a meaningful first-pass review in under thirty seconds, before you have even opened the browser.
Minute 20–25: File Operations
Reading and Summarising Files
Gemini CLI can work with multiple files simultaneously. Point it at a directory:
gemini "Summarise the purpose of each .js file in the current directory."
Or be explicit about which files to consider:
gemini "Compare utils.js and app.js. Are there any duplicated functions between them?"
Writing Files
With --write mode, Gemini CLI can create new files from scratch:
gemini --write "Create a constants.js file that exports all magic numbers and strings currently hardcoded in utils.js."
The model will scan utils.js, identify hardcoded values, create constants.js with named exports, and produce the updated utils.js that imports from constants.js instead. You confirm the diff before anything changes.
Batch Operations
Batch operations follow a consistent pattern: describe what you want done across multiple files.
gemini --write "Add JSDoc comments to every exported function in utils.js. Follow the JSDoc standard format with @param and @returns tags."
For multiple files:
gemini --write "Add a one-line JSDoc comment to every function in every .js file in the src/ directory."
Gemini CLI will read each file, generate the appropriate comments for each function, and show you a unified diff across all changed files before writing anything.
Renaming and Restructuring
Restructuring is where --write mode earns its keep:
gemini --write "Rename the chunk function in utils.js to chunkArray everywhere it is used in this project."
The model will find all usages across files, update every reference, and show you the complete change before applying it. This is not as robust as a dedicated refactoring tool with full AST support, but for small-to-medium projects it covers the common case well.
Minute 25–30: Building a Workflow
This final section combines everything you have learned into a realistic, end-to-end task: auditing a JavaScript utility file, fixing the issues found, adding tests, and documenting the result.
Step 1: Audit
gemini "Audit utils.js for code quality, edge-case handling, and documentation gaps. Return a numbered list of issues."
Save the output — you will reference it in the next step.
Step 2: Fix
gemini --write "Fix all the issues listed below in utils.js:
1. parseDate does not handle null or undefined input.
2. slugify produces double hyphens when input has leading or trailing spaces.
3. chunk does not validate that size is a positive integer.
4. No function has JSDoc documentation."
Gemini CLI applies all four fixes in a single pass. Inspect the diff, confirm, and the file is updated.
Step 3: Generate Tests
gemini --write "Write a complete Jest test file for the updated utils.js. Name it utils.test.js. Every fix from the previous step should have at least one corresponding test."
Step 4: Verify
npx jest utils.test.js --coverage 2>&1 | gemini "Are all functions fully covered? If not, what tests should be added?"
Step 5: Generate a Changelog Entry
git diff | gemini "Write a CHANGELOG entry for these changes in Keep a Changelog format."
That five-step workflow — audit, fix, test, verify, document — is one you can run on any file, in any project, in under five minutes once you are comfortable with the commands. The pattern scales from a single utility function to an entire module.
Next Steps
You now have a working foundation. Here are the three directions worth exploring next:
Plan Mode
Plan Mode (gemini --plan) is for larger, multi-step tasks. Instead of executing immediately, Gemini CLI first shows you a structured plan — which files it will read, what changes it will make, in what order — and asks for your approval before doing anything. Use Plan Mode whenever a task touches more than two or three files or involves changes you cannot easily reverse.
gemini --plan "Refactor the authentication module to use JWT tokens instead of session cookies."
MCP Servers
The Model Context Protocol lets Gemini CLI connect to external tools and data sources: GitHub, Jira, Postgres, Slack, and any custom API you build. Once an MCP server is configured, you can ask Gemini CLI to perform actions across those systems mid-conversation.
# After configuring the GitHub MCP server:
gemini "Open a GitHub issue for each TODO comment in utils.js."
MCP is covered in depth in the Complete Guide to Gemini CLI MCP Servers.
Automation and CI Integration
Gemini CLI works well inside CI pipelines. A common pattern is to run it as a pre-merge code review step:
# In a GitHub Actions workflow:
- name: AI code review
run: gh pr diff ${{ github.event.pull_request.number }} | gemini "Review for correctness and security issues. Exit with code 1 if critical issues are found."
You can also use it to automate documentation generation, changelog creation, and dependency update summaries on a schedule.
5 Essential Patterns
These five patterns cover the vast majority of everyday Gemini CLI use. Learn them first; explore everything else second.
Pattern 1: The File Question
gemini "Your question about the file." < somefile.txt
# or
cat somefile.txt | gemini "Your question."
Use this whenever you want to ask anything about the content of a file without quoting the content in the prompt.
Pattern 2: The Command Output Pipe
some-command 2>&1 | gemini "Interpret this output and tell me what to do next."
Feed error logs, test results, compiler output, or any CLI output directly into Gemini CLI for instant interpretation. The 2>&1 redirect ensures stderr is included alongside stdout.
Pattern 3: The Contextual Edit
gemini --write "Make a specific, scoped change to filename.ext."
Always be specific about which file and what change. Vague prompts produce vague edits. "Add input validation to the createUser function in routes/users.js" is better than "add input validation".
Pattern 4: The Git Diff Review
git diff | gemini "Review this diff for issues before I commit."
# or review the last commit:
git show | gemini "Review this commit for issues."
Build this into your pre-commit habit. It catches the kind of small issues — off-by-one errors, missing error handling, typos in variable names — that are embarrassing to push and tedious to fix after the fact.
Pattern 5: The Exploratory Question
gemini "I'm in an unfamiliar codebase. Explain how the authentication system works based on the files in src/auth/."
Use this pattern at the start of any session in an unfamiliar project. Gemini CLI will read the relevant files and produce a narrative explanation that would otherwise take you fifteen minutes to piece together from reading source code.
FAQ
Q: Does Gemini CLI send my source code to Google's servers?
Yes — the content you include in a prompt, whether typed directly or piped from a file, is sent to the Gemini API to generate a response. Review your organisation's data handling policies before using Gemini CLI with proprietary or sensitive code. For most open-source and personal projects, this is not a concern.
Q: How does Gemini CLI know which files to read when I don't specify them?
When you run gemini from a project directory, the CLI makes the current directory's file tree available as context. It reads files that seem relevant based on your question — typically entry points, configuration files, and files whose names match keywords in your prompt. You can always be explicit by naming files directly in the prompt or using the pipe/redirect pattern.
Q: Can I use Gemini CLI offline?
No. Every query requires a network connection to the Gemini API. There is no local inference mode. If offline capability matters for your workflow, you may want to pair Gemini CLI with a locally-hosted model via an MCP server, but that is an advanced configuration outside the scope of this guide.
Q: The --write flag makes me nervous. Can I preview changes without applying them?
Yes. Run any --write prompt without the flag first to see the suggested changes in your terminal. When you are ready to apply, re-run with --write. Alternatively, --write itself always shows a diff and asks for explicit confirmation before modifying any file — you can review and reject at that step.
Q: How do I handle a codebase that is too large to fit in context?
Gemini CLI's context window is large (up to 1 million tokens with Gemini 2.5 Pro), but no context window is infinite. For very large codebases, the two most effective strategies are: (1) navigate to the subdirectory most relevant to your task before running Gemini CLI, reducing the file tree it considers; (2) use MCP server tools like the filesystem server to explicitly control which files are loaded rather than letting the CLI infer relevance.
Conclusion
Thirty minutes ago you had never run Gemini CLI. You have now installed it, authenticated, asked your first question, analysed a real file, generated and tested code, found bugs via pipe, operated on files directly, and assembled a complete audit-and-fix workflow.
That is a solid foundation. Most developers who use Gemini CLI daily stay within the five core patterns described in this guide for eighty percent of their work. The advanced features — Plan Mode, MCP servers, CI automation — are genuinely powerful, but they build on the same mental model you have just developed.
The best way to continue learning is to bring the tool into your actual work rather than running contrived exercises. The next time you need to understand an unfamiliar file, reach for Gemini CLI instead of reading it cold. The next time you write a function, ask Gemini CLI for tests before you write them yourself. The next time you see a failing build in CI, pipe the error output and ask what is wrong.
Each of those small substitutions deepens familiarity, and familiarity is what turns a tool you installed into a tool you depend on.

Zhihao Mu
· Full-stack DeveloperDeveloper and technical writer passionate about AI-powered development tools. Building geminicli.one to help developers unlock the full potential of Gemini CLI.
GitHub ProfileWas this article helpful?