GC-201c · Module 1
Headless Mode Deep Dive
4 min read
The -p flag is the gateway to Gemini CLI automation. Pass a prompt as a string, Gemini processes it, outputs the result, and exits. No interactive session, no conversation history, no human in the loop. This single flag transforms Gemini CLI from a chat interface into a Unix-style command that composes with pipes, redirects, and shell scripts. Every automation pattern in this course builds on this foundation.
The --output-format flag controls how Gemini structures its response. "text" (default) produces human-readable output. "json" wraps the response in a structured JSON object — parseable by jq, Python, Node.js, or any JSON-aware tool. "stream-json" produces streaming JSON — each chunk is a valid JSON object, useful for real-time processing of long responses. For automation, always use json or stream-json. Text output is for terminals. JSON output is for scripts.
# Basic headless execution
gemini -p "Explain what this project does based on the README"
# JSON output for scripting
gemini -p "List all exported functions in src/api/" --output-format json
# Pipe to jq for extraction
gemini -p "Analyze the package.json dependencies" --output-format json | jq '.response'
# Redirect to file
gemini -p "Generate API documentation for src/routes/" > docs/api.md
# Use in conditionals
if gemini -p "Does this code have SQL injection vulnerabilities? Answer YES or NO only" | grep -q "YES"; then
echo "::error::SQL injection vulnerability detected"
exit 1
fi
Do This
- Use --output-format json for any output that feeds into another script
- Pipe specific context into prompts rather than relying on session state
- Use exit codes and grep to create conditional workflows
Avoid This
- Parse text output with regex when structured JSON is available
- Assume headless mode remembers previous invocations — it does not
- Use headless mode for tasks that require multi-turn conversation