Skip to main content
Headless mode provides a programmatic interface to Gemini CLI, returning structured text or JSON output without an interactive terminal UI.

Technical Reference

Headless mode is triggered when the CLI is run in a non-TTY environment or when providing a query as a positional argument without the interactive flag.

Output Formats

You can specify the output format using the --output-format flag.

JSON Output

Returns a single JSON object containing the response and usage statistics. Schema:
response
string
The model’s final answer.
stats
object
Token usage and API latency metrics.
error
object
Error details if the request failed (optional).
Example usage:
gemini "What is the capital of France?" --output-format json
Example output:
{
  "response": "The capital of France is Paris.",
  "stats": {
    "inputTokens": 12,
    "outputTokens": 8,
    "totalTokens": 20,
    "apiLatencyMs": 234
  }
}

Streaming JSON Output

Returns a stream of newline-delimited JSON (JSONL) events. Event types:
init
object
Session metadata (session ID, model).
message
object
User and assistant message chunks.
tool_use
object
Tool call requests with arguments.
tool_result
object
Output from executed tools.
error
object
Non-fatal warnings and system errors.
result
object
Final outcome with aggregated statistics.
Example usage:
gemini "List files in current directory" --output-format json-stream
Example output:
{"type":"init","sessionId":"abc123","model":"gemini-2.0-flash-exp"}
{"type":"message","role":"assistant","content":"I'll list the files"}
{"type":"tool_use","name":"bash","args":{"command":"ls"}}
{"type":"tool_result","output":"file1.txt\nfile2.txt"}
{"type":"message","role":"assistant","content":"Found 2 files"}
{"type":"result","stats":{"totalTokens":150}}

Exit Codes

The CLI returns standard exit codes to indicate the result of the headless execution:
0
exit code
Success.
1
exit code
General error or API failure.
42
exit code
Input error (invalid prompt or arguments).
53
exit code
Turn limit exceeded.
Example usage in scripts:
#!/bin/bash

gemini "Analyze this code" --output-format json > output.json

if [ $? -eq 0 ]; then
  echo "Success!"
  cat output.json | jq '.response'
else
  echo "Failed with exit code: $?"
  exit 1
fi

Common Use Cases

CI/CD Integration

Automate code reviews, changelog generation, or test creation in your CI pipeline.

Batch Processing

Process multiple files or inputs in a loop for consistent analysis or transformation.

API Wrapper

Build custom APIs or services on top of Gemini CLI capabilities.

Monitoring & Alerts

Generate reports or summaries from logs and system data.

Next Steps

CLI Reference

See all available flags and options for headless mode

Build docs developers (and LLMs) love