How to Use Grok CLI in Bash Scripts and Cron Jobs
Grok CLI can run non-interactively, which means you can call it from a bash script or a cron job to generate commands, summarize logs, or convert data on a schedule. The catch is that unattended runs have no human to catch a bad command, so guardrails matter more than they do interactively.
Interactive use is covered in the setup guide to Grok CLI. This is about making it reliable when no one is watching.
How Do You Call It Non-Interactively?
Pass the prompt as an argument or via stdin and capture stdout. The pattern is the same as any command-line tool.
#!/usr/bin/env bash
set -euo pipefail
OUT=$(grok-cli -p "summarize this log in 3 bullet points: $(tail -n 200 /var/log/app.log)")
echo "$OUT" | mail -s "nightly log summary" me@example.com
Capture output to a variable or file. Never let it execute a generated command directly in an unattended context — read-only generation only.
How Do You Handle Failures in Cron?
Cron runs with a minimal environment, which breaks scripts that work fine in your shell. Two fixes: use absolute paths to the binary, and load your environment explicitly.
- Set
PATHat the top of the script. - Export the API key from a file you source, not from your interactive profile.
- Use
set -euo pipefailso a failed call stops the script. - Log everything to a file with timestamps.
Without these, a cron job that “works” in testing fails silently the first night it matters.
What Should You Automate — and What Shouldn’t You?
| Good fit | Poor fit |
|---|---|
| Summarizing logs | Deleting or moving files |
| Drafting commit messages | Running sudo commands |
| Converting data formats | Anything destructive |
Keep automated calls read-only or additive. The moment a scheduled AI step can modify or delete, you have built a system that can fail destructively with no supervision.
How Do You Control Cost in a Loop?
A cron job that runs every minute with a large log input adds up. Cap the input size (tail the last N lines), keep the prompt short, and schedule at a frequency you would actually read the output. Generating a summary nobody looks at is pure waste.
Key Takeaways
- Grok CLI supports non-interactive calls for scripts and cron.
- Cron needs absolute paths and an explicit environment; do not rely on your shell profile.
- Use
set -euo pipefailand log with timestamps. - Automate read-only or additive tasks — never destructive ones.
- Cap input size and schedule frequency to control token cost.
