Grok Build CLI: Headless Mode and Automation
Everything Grok does interactively, it can do from a script. Headless mode takes a single prompt, runs it with full tool access, and returns the result, perfect for CI pipelines, pre-commit hooks, and batch jobs. This is where Grok stops being a tool you use and becomes infrastructure you build on.
New to the series? Start at Grok Build CLI: Zero to Hero (Start Here).
The basics
The -p flag triggers headless mode. Choose an output format, pipe content in, parse results out. JSON output gives you the response text plus a session id you can resume.
There are three formats: plain for humans, json for a single structured object, and streaming-json for a real-time NDJSON event stream you can process line by line.
Keep context across calls
Each grok -p is a fresh session by default. Give it a name with -s and the next call with the same id picks up where you left off. This is the backbone of multi-step automation.
Lock down the toolset
Headless runs should only have the tools they need. Use --tools as an allowlist or --disallowed-tools as a denylist. You can even block subagent spawning by type. Pair these with --max-turns to cap how long a run can go.
Built for CI
For unattended runs, --yolo auto-approves every tool. Combine it with --rules to set guardrails, and parse the JSON output with jq to gate your pipeline. Exit codes are meaningful: 0 for success, 1 for errors, 130 for an interrupt, 143 for termination, so CI can tell a real failure from a cancellation.
For air-gapped or read-only containers, mount ~/.grok read-only, set XAI_API_KEY, and add --no-auto-update. Update messages go to stderr, so stdout stays clean for --output-format json.
The safest automation stack pairs headless mode with permission rules and an OS sandbox. That is the next part.
Continue the series
The full series
- Grok Build CLI: Zero to Hero (Start Here)
- Grok Build CLI: Sessions, Rewind and Compaction
- Grok Build CLI: Slash Commands and Keyboard Mastery
- Grok Build CLI: Teaching Grok Your Project (AGENTS.md)
- Grok Build CLI: Models and Custom Endpoints
- Grok Build CLI: Extending Grok with MCP, Skills, Plugins and Hooks
- Grok Build CLI: Cross-Session Memory
- Grok Build CLI: Subagents, Plan Mode and Background Work
- Grok Build CLI: Headless Mode and Automation (you are here)
- Grok Build CLI: Sandbox and Permissions
- Grok Build CLI: IDE Integration with ACP
- Grok Build CLI: The Evolution (Power-User Version History)