Guide · Grok Build
How to run Grok Build headless (non-interactive): scripts, cron and CI
Grok Build is built for an interactive terminal. But when you want to automate routine maintenance, run Grok CLI non-interactive workflows, or run Grok Build in CI pipelines, you need it to run without a human typing answers. Here is how to run Grok Build headless from scripts, cron, and CI using grok -p and a few automation flags.
What headless mode is
By default, launching grok starts an interactive fullscreen terminal interface (TUI). The agent renders progress spinners, streams tokens into an interactive viewport, and waits for keyboard input whenever an action or tool call requires your approval.
Headless mode (also referred to as running the Grok CLI non-interactive) runs Grok Build without launching the TUI. The process accepts a prompt via command-line arguments or a file, executes the necessary agent turns in the background, prints the response directly to stdout, and terminates with a standard process exit code.
Grok provides two main entry points for non-interactive execution: single-turn execution with the -p or --prompt-file flags on the main grok binary, and the dedicated grok agent subcommand (which includes subcommands like stdio, headless, serve, and leader). For shell scripts, crontabs, and continuous integration runners, passing -p or --prompt-file directly to grok is the cleanest and most common approach.
One-shot prompt with -p
The most direct way to run Grok Build headless is with the -p (or --single) flag. Running grok -p executes a single-turn prompt, prints the agent's response to stdout, and exits:
Copy this and paste it on that computer. You do not need to type it by hand.
grok -p "Check git status and summarize recent commits on this branch"By default, Grok runs in your current shell directory. If your script or cron runner lives elsewhere, use --cwd <CWD> to set the working directory without changing the caller's working directory:
Copy this and paste it on that computer. You do not need to type it by hand.
grok --cwd /var/www/my-project -p "Run npm test and report any failing test suites"You can also pick a model with -m (run grok models to list the IDs your plan has), or create an isolated git worktree for the session using -w (or --worktree [<WORKTREE>]):
Copy this and paste it on that computer. You do not need to type it by hand.
grok -w audit-worktree -p "Scan src/ for deprecated API usages"When Grok finishes, it outputs the model's response to stdout and returns control to your shell.
Prompt from a file
Passing long instructions, structured review rubrics, or multi-line tasks inside inline shell strings quickly becomes unwieldy. Grok provides --prompt-file <PATH> to read the initial single-turn prompt directly from a text file:
Copy this and paste it on that computer. You do not need to type it by hand.
grok --prompt-file ./scripts/prompts/nightly-audit.txtThis approach keeps prompts cleanly versioned in your repository. If you have extra instructions or guidelines that should apply across multiple automated runs without bloating individual prompt files, use --rules <RULES> to append custom rules to the system prompt:
Copy this and paste it on that computer. You do not need to type it by hand.
grok --prompt-file ./scripts/prompts/review.txt --rules "Never edit package.json directly; report findings in markdown."JSON output and parsing with jq
By default, headless Grok outputs human-readable plain text (--output-format plain). When integrating Grok Build into larger automation pipelines, you often need machine-readable structured output.
Grok provides the --output-format flag with four supported values: plain, json, streaming-json, and streaming-messages-json. Choosing json emits the agent's turn result as a structured JSON object:
Copy this and paste it on that computer. You do not need to type it by hand.
grok -p "Analyze package.json for outdated packages" --output-format jsonYou can pipe this output into jq. Field names can change between releases, so inspect one real run with jq . before you write a filter that picks fields out:
Copy this and paste it on that computer. You do not need to type it by hand.
grok -p "List all exported TypeScript types in packages/shared/src/index.ts" \
--output-format json | jq .If your pipeline requires strict output conformity, pass a JSON schema string with --json-schema <SCHEMA>. Grok constrains the response to match your schema, making it safe to parse in downstream shell scripts or automated workflows.
Permissions safely: allow rules vs bypass
When running interactively, Grok pauses and asks for confirmation before modifying files or executing shell commands. In headless scripts and unattended cron jobs, there is no interactive terminal session to answer permission prompts.
Grok provides several knobs to control permissions:
--permission-mode <MODE>: Selects the permission strategy (supported values:default,acceptEdits,auto,dontAsk,bypassPermissions,plan).--always-approve: Automatically approves all tool executions.--allow <RULE>: Adds a specific permission allow rule.--deny <RULE>: Adds a specific permission deny rule.--tools <TOOLS>: Restricts which built-in tools are available (comma-separated list).--sandbox <PROFILE>: Sets the sandbox profile for filesystem and network access.
Warning: Be very careful with --always-approve or --permission-mode bypassPermissions. If your prompt processes untrusted input (such as git commit messages, issue descriptions, or external PR data), an unconstrained agent could execute destructive shell commands or overwrite critical files.
Instead, follow the principle of least privilege. Prefer safer modes like --permission-mode acceptEdits (which permits file edits without prompting for each file write) or combine --permission-mode auto with explicit --allow and --deny rules. For a read-only audit, plan mode keeps the agent from changing anything:
Copy this and paste it on that computer. You do not need to type it by hand.
grok -p "Audit the repository structure and list duplicate files" \
--permission-mode planLimiting turns with --max-turns
In unattended environments, an agent might attempt to resolve a complex compiler error or failing test across dozens of reasoning loops. Without limits, a looping agent consumes excessive API quota or runs until the host machine hits a script timeout.
Set a ceiling with --max-turns <N>:
Copy this and paste it on that computer. You do not need to type it by hand.
grok -p "Run npm run build and attempt to fix type errors" \
--permission-mode acceptEdits \
--max-turns 4If Grok reaches the turn limit before finishing, it stops there, so check the output and exit code before trusting the result. For robust scripting, combine --max-turns with standard Unix process timeouts like timeout 300s grok -p ... to prevent runaway processes if a network call hangs.
Continuing a session
Headless runs do not vanish when the process exits. Grok records session state in its local storage directory (~/.grok). This allows multi-stage scripts to chain prompts, or allows you to inspect an automated headless run in your interactive terminal later.
-c, --continue: Continues the most recent session for the current working directory.-r, --resume [<SESSION_ID_OR_TITLE>]: Resumes a specific session by ID or title, or the most recent session if omitted.-s, --session-id <SESSION_ID>: Assigns an explicit UUID to a new session, so downstream steps know the exact ID to resume.--fork-session: Creates a new branched session ID when resuming, preserving the original session intact.
For example, you can create a session in an initial script step and follow up in a subsequent step:
Copy this and paste it on that computer. You do not need to type it by hand.
TASK_ID=$(uuidgen)
grok -s "$TASK_ID" -p "Analyze src/components/ for accessibility issues" --max-turns 3
grok -r "$TASK_ID" -p "Now write a summary report to accessibility-report.md" --permission-mode acceptEditsIf an automated run fails or needs human attention, you can open your terminal, run grok -r "$TASK_ID", and pick up the conversation interactively.
Running from cron
To run Grok Build on a schedule, you can configure a standard Linux crontab entry. However, cron executes in a minimal environment that lacks your interactive shell configuration and environment variables.
Keep these rules in mind when writing a crontab for Grok:
- Use absolute paths: Specify the full path to the
grokexecutable (usually/usr/local/bin/grokor/home/username/.local/bin/grok). - Set working directory: Use
cd /path/to/project &&or the--cwdflag so Grok finds the target repository and its git configuration. - Keep the machine awake: Cron only triggers if the computer is turned on and awake. A sleeping laptop will skip scheduled jobs.
- Preserve credentials: Grok stores its login session under
~/.grok. Make sure the cron job runs under the user account where you rangrok login, and ensureHOMEis set. - Redirect output: Redirect both stdout and stderr (
2>&1) to a log file so you can debug failures.
Here is an example crontab entry running a test check every weekday at 3:00 AM:
Copy this and paste it on that computer. You do not need to type it by hand.
0 3 * * 1-5 cd /home/ubuntu/apps/web && /usr/local/bin/grok -p "Run npm test and write any failures to test-failures.log" --max-turns 5 --permission-mode acceptEdits >> /home/ubuntu/logs/grok-cron.log 2>&1Running in CI
A frequent reason to run Grok Build headless is automated continuous integration. You can run Grok Build in CI pipelines (such as GitHub Actions, GitLab CI, or local build workers) to perform automated code reviews, check documentation consistency, or inspect pull request diffs.
A generic CI shell step looks like this:
Copy this and paste it on that computer. You do not need to type it by hand.
- name: Run Grok Build automated review
run: |
grok -p "Review git diff origin/main...HEAD for security flaws and performance regressions" \
--permission-mode auto \
--max-turns 4 \
--output-format plainAuthentication in CI: The runner environment must have valid Grok credentials before executing commands. Because authentication mechanisms depend on how your organization provisions credentials, refer to Grok's official documentation for supported CI authentication options and login credentials. Ensure your runner does not expose secrets in build logs or print sensitive prompt files.
Caveats of headless operation
Running an autonomous coding agent headlessly requires care:
- No prompt confirmation: Unattended runs cannot ask you for clarification. If your prompt is ambiguous, the agent will do its best guess.
- Silent failures: If authentication in
~/.grokexpires or the network drops, your cron job will exit with an error. Always check exit codes and monitor output logs. - Destructive edits without git: If you allow file modifications without interactive confirmation, always make sure the repository is clean or committed first so you can
git resetif needed. - Usage limits: Long-running tasks without
--max-turnscan consume your monthly allowance or token quota unexpectedly.
Don't want to keep a terminal or cron box around?
Writing shell scripts, managing crontabs, monitoring log files, and keeping a dedicated terminal or cron box awake takes ongoing maintenance. If you want scheduled agent runs without managing crontabs or running headless scripts yourself, AgentPort offers a simpler approach.
AgentPort runs Grok Build (and Google Antigravity) on your own computer or server and gives you a phone and web chat interface. With Routines, you can run prompts on an automated cron schedule or trigger them from webhooks:
- Free plan: Up to 2 routines per computer, scheduled at most hourly.
- Pro plan: Up to 20 routines per computer, scheduled as often as every 5 minutes, plus webhook HTTP triggers.
Every routine run produces a full chat session that you can open from your phone or browser to inspect diffs and continue the conversation whenever you want. Learn more about schedules in Schedule an AI coding agent on your computer with cron, webhook triggers in Trigger an AI coding agent from a GitHub or Stripe webhook, or compare plans on our pricing page.
FAQ
What is the difference between grok -p and grok agent?
grok -p (or --single) runs a single-turn prompt in the foreground, streams the output to stdout, and terminates when finished. The grok agent subcommand is a lower-level command that runs the agent without the UI over stdio, as a WebSocket server, or connected to a background leader process.
Can Grok Build edit files in headless mode?
Yes, if you configure the permission mode appropriately. Using --permission-mode acceptEdits or --always-approve allows Grok to write changes to disk without pausing for interactive confirmation. Keep your repository committed to git so you can review changes with git diff.
Does grok -p save my conversation history?
Yes. Grok stores session transcripts locally in ~/.grok. You can resume the conversation later by passing -c (or --continue) or -r <SESSION_ID>, either from another script or directly inside the interactive TUI.
Why does my cron job fail with "command not found"?
Linux cron executes commands with a minimal PATH environment variable. Always provide the full absolute path to the Grok executable (such as /usr/local/bin/grok), set HOME so Grok finds its login token, and redirect stderr to a log file to capture errors.
Try it on your own computer
The Free plan covers 1 computer. Pro is $27/month for up to 3. You bring the AI login and pay that provider directly.