- Posted on
- • Artificial Intelligence
Artificial Intelligence Bash Scripts Every Sysadmin Should Know
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Bash Scripts Every Sysadmin Should Know
Drowning in alerts, sifting through endless logs, and explaining arcane diffs at 3 a.m.? You don’t need a full-blown platform to get value from AI. A few small Bash scripts can turn large mountains of operational noise into clear, actionable insights—right from your terminal.
This article shows how to glue modern AI models (local or cloud) to the Unix toolbox using nothing more than curl, jq, and a handful of careful prompts. You’ll get ready-to-use scripts for log summarization, alert triage, config-diff explanations, natural-language-to-command suggestions, and a lightweight runbook Q&A. Each example is short, auditable, and designed to keep you in control.
Why AI-in-Bash is worth your time
It meets you where you work: SSH, shell, pipelines, and stdout.
It’s flexible: swap between local models (for privacy) and cloud models (for quality) without rewriting scripts.
It pays off fast: 10–30-line helpers can save hours per incident.
It’s safe-by-default if you add human-in-the-loop checks and avoid auto-execution.
Prerequisites and setup
We’ll use standard CLI tools. Install them with your package manager.
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y curl jq ripgrep git python3-pipx
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y curl jq ripgrep git python3-pipx
- openSUSE/SLES (zypper):
sudo zypper refresh
sudo zypper install -y curl jq ripgrep git python3-pipx
Optional (cloud CLI):
- Ensure pipx is on your PATH, then:
pipx install openai
Optional (local model via Ollama):
curl -fsSL https://ollama.com/install.sh | sh
sudo systemctl enable --now ollama
ollama pull llama3:latest
Environment you’ll need for the scripts:
For local models with Ollama:
- LLM_PROVIDER=ollama
- OLLAMA_URL=http://localhost:11434 (default)
- LLM_MODEL=llama3:latest (or another pulled model)
For cloud models (OpenAI-compatible):
- LLM_PROVIDER=openai
- OPENAI_BASE_URL=https://api.openai.com/v1 (or your compatible endpoint)
- OPENAI_API_KEY=sk-...
- LLM_MODEL=gpt-4o-mini (or your preferred model)
A tiny LLM adapter that everything uses
Drop this helper in your $PATH as llm.sh and make it executable. All scripts below just pipe a prompt into it.
#!/usr/bin/env bash
# llm.sh — minimal LLM adapter (Ollama or OpenAI-compatible)
set -euo pipefail
: "${LLM_PROVIDER:=ollama}"
: "${LLM_MODEL:=llama3:latest}"
: "${OLLAMA_URL:=http://localhost:11434}"
: "${OPENAI_BASE_URL:=https://api.openai.com/v1}"
: "${OPENAI_API_KEY:=}"
prompt="$(cat)"
if [[ "$LLM_PROVIDER" == "ollama" ]]; then
curl -sS "$OLLAMA_URL/api/generate" \
-H 'Content-Type: application/json' \
-d "$(jq -n --arg m "$LLM_MODEL" --arg p "$prompt" '{model:$m, prompt:$p, stream:false}')" \
| jq -r '.response'
elif [[ "$LLM_PROVIDER" == "openai" ]]; then
if [[ -z "$OPENAI_API_KEY" ]]; then
echo "OPENAI_API_KEY is required for provider=openai" >&2
exit 1
fi
curl -sS "$OPENAI_BASE_URL/chat/completions" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H 'Content-Type: application/json' \
-d "$(jq -n --arg m "$LLM_MODEL" --arg p "$prompt" \
'{model:$m, messages:[{role:"system",content:"You are a concise Linux ops assistant."},
{role:"user",content:$p}],
temperature:0.2}')" \
| jq -r '.choices[0].message.content'
else
echo "Unknown LLM_PROVIDER: $LLM_PROVIDER" >&2
exit 1
fi
Usage:
echo "Explain why nginx might return 502 under load and list checks" | ./llm.sh
1) Log summarizer with root-cause hints
Goal: Reduce 2,000 noisy lines of logs into a one-minute briefing with likely causes and next steps.
Save as log_summarize.sh:
#!/usr/bin/env bash
# log_summarize.sh — summarize logs and suggest next steps
set -euo pipefail
LINES="${LINES:-400}" # tail this many lines from stdin
log_snippet="$(cat | tail -n "$LINES")"
read -r -d '' prompt <<'P'
You are an SRE assistant. Given a log excerpt:
- Summarize what is happening (concise).
- List 2–4 likely root-cause hypotheses with reasoning.
- Identify impacted components/services.
- Propose the top 3 actionable next steps (commands or checks).
- If logs look normal/benign, say so.
P
printf "%s\n\nLog excerpt (last %s lines):\n---\n%s\n---\n" \
"$prompt" "$LINES" "$log_snippet" | ./llm.sh
Examples:
journalctl -u nginx --since "30 min ago" | ./log_summarize.sh
tail -n 1000 /var/log/syslog | LINES=300 ./log_summarize.sh
Tip: Prefer local models (Ollama) for sensitive logs. If you must use cloud, redact secrets first.
2) Config change and diff explainer
Goal: Explain what a diff is doing and any risks before you deploy.
Save as diff_explain.sh:
#!/usr/bin/env bash
# diff_explain.sh — explain risk and intent of a diff from stdin
set -euo pipefail
# Strip color codes that might confuse the model
diff_input="$(sed -r 's/\x1B\[[0-9;]*[mK]//g' </dev/stdin)"
read -r -d '' prompt <<'P'
You are reviewing a configuration or code diff.
- Briefly summarize the intent of the changes.
- Call out potential risks, roll-back considerations, and blast radius.
- Note any missing safeguards (e.g., rate limits, timeouts).
- Suggest quick validation commands/checks post-deploy.
Respond in bullet points.
P
printf "%s\n\nDiff:\n---\n%s\n---\n" "$prompt" "$diff_input" | ./llm.sh
Examples:
git diff --staged | ./diff_explain.sh
git show HEAD | ./diff_explain.sh
diff -u /etc/nginx/nginx.conf{.old,} | ./diff_explain.sh
3) Alert triage and routing (JSON out)
Goal: Group similar alerts and propose severity and owner tags to cut through alert storms.
Save as alert_triage.sh:
#!/usr/bin/env bash
# alert_triage.sh — group and score alerts from stdin, JSON output
set -euo pipefail
alerts="$(cat)"
read -r -d '' prompt <<'P'
You will receive raw alert lines. Group similar alerts and output compact JSON with:
- groups: [
{ "reason": "...", "examples": ["...","..."],
"severity": "low|medium|high|critical",
"owner": "team/service guess",
"suggested_action": "one-liner next step" }
]
Rules:
- Be conservative with severity if uncertain.
- Prefer existing team/service names when obvious (db, web, cache, network).
- Output ONLY JSON.
P
printf "%s\n\nAlerts:\n---\n%s\n---\n" "$prompt" "$alerts" | ./llm.sh
Examples:
# Pipe recent alerts into triage
grep -h "ALERT" /var/log/*.log | tail -n 200 | ./alert_triage.sh | jq
Note: Keep a human in the loop—this is a prioritization hint, not a pager gatekeeper.
4) Natural language to command (suggest-only, never auto-runs)
Goal: Turn “check which process is using port 8080” into a safe, explainable command suggestion.
Save as nlc.sh:
#!/usr/bin/env bash
# nlc.sh — natural language to command suggestion (confirm before run)
set -euo pipefail
query="${*:-}"
if [[ -z "$query" ]]; then
echo "Usage: $0 <what you want to do>" >&2
exit 1
fi
read -r -d '' prompt <<'P'
You are a Linux shell assistant. Given a request, propose ONE safe, non-destructive command.
- Prefer read-only checks, --dry-run flags, and defaults that won't modify state.
- Use widely available tools. If root is required, prepend `sudo`.
- Output in this format only:
COMMAND: <single-line command>
WHY: <short explanation>
P
resp="$(printf "%s\n\nRequest: %s\n" "$prompt" "$query" | ./llm.sh)"
cmd="$(printf "%s\n" "$resp" | sed -n 's/^COMMAND:[[:space:]]*//p' | head -n1)"
why="$(printf "%s\n" "$resp" | sed -n 's/^WHY:[[:space:]]*//p')"
echo "Suggestion:"
echo " $cmd"
echo "Reason:"
echo " $why"
echo
# safety checks
if [[ -z "$cmd" ]]; then
echo "No command suggested." >&2
exit 1
fi
# basic guard: verify the binary exists
bin="${cmd%% *}"
if ! command -v "$bin" >/dev/null 2>&1; then
echo "Warning: '$bin' not found in PATH." >&2
fi
read -r -p "Run this command? [y/N] " ans
if [[ "$ans" =~ ^[Yy]$ ]]; then
set -x
eval "$cmd"
else
echo "Aborted."
fi
Examples:
./nlc.sh "show which process is listening on port 8080"
./nlc.sh "estimate disk usage per directory under /var/log, top 5"
5) Runbook Q&A with RAG-lite (ripgrep + LLM)
Goal: Answer “how do I rotate Kafka certs here?” by searching your runbooks and asking the model to synthesize instructions, citing files.
Save as runbook_qa.sh:
#!/usr/bin/env bash
# runbook_qa.sh — search runbooks and ask LLM to synthesize an answer
set -euo pipefail
RUNBOOK_DIR="${RUNBOOK_DIR:-/srv/runbooks}"
QUERY="${*:-}"
if [[ -z "$QUERY" ]]; then
echo "Usage: RUNBOOK_DIR=/path/to/runbooks $0 <question>" >&2
exit 1
fi
if [[ ! -d "$RUNBOOK_DIR" ]]; then
echo "Runbook dir not found: $RUNBOOK_DIR" >&2
exit 1
fi
# Get top matching snippets with context
matches="$(rg -n --no-heading -C 2 -m 8 -e "$QUERY" "$RUNBOOK_DIR" 2>/dev/null | head -n 400)"
read -r -d '' prompt <<'P'
You are a site reliability assistant. Using the provided runbook snippets, answer the question for THIS environment.
- Synthesize clear, step-by-step instructions.
- Cite file paths and line numbers where relevant.
- If info is missing or ambiguous, say what else is needed.
P
printf "%s\n\nQuestion: %s\n\nRelevant snippets:\n---\n%s\n---\n" \
"$prompt" "$QUERY" "$matches" | ./llm.sh
Examples:
RUNBOOK_DIR=/srv/runbooks ./runbook_qa.sh "rotate Kafka TLS certs"
RUNBOOK_DIR=./docs/runbooks ./runbook_qa.sh "recover from etcd quorum loss"
Tip: Keep your runbooks in git and up to date; this script becomes dramatically more useful over time.
Security, privacy, and reliability notes
Prefer local models (Ollama) for sensitive logs and configs.
Redact tokens, IPs, and PII before sending data to cloud APIs.
Never auto-execute LLM output without human confirmation. The nlc.sh script defaults to “don’t run.”
Log and version-control your prompts where appropriate; small wording changes can affect results.
Use temperature ~0.0–0.3 for predictable, terse answers.
Troubleshooting
jq not found: install via your package manager (see prerequisites).
Ollama connection refused: ensure the service is running:
- systemctl status ollama
JSON parsing weirdness: many models occasionally emit extra text; keep prompts strict (e.g., “Output ONLY JSON”). Consider adding jq fallback guards.
Cloud 401 errors: check OPENAI_API_KEY and OPENAI_BASE_URL.
Conclusion and next steps
Small, auditable Bash scripts can give you 80% of the AI-on-ops value with 20% of the effort. Start with one:
Put llm.sh in your PATH.
Pick either local Ollama or a cloud API.
Wire log_summarize.sh into your incident workflow.
Add diff_explain.sh to your pre-merge or pre-deploy checks.
Keep humans in the loop.
Then iterate. Wrap outputs into tmux panes, cron a daily digest, or feed triaged alerts into your ticketing system. When you find a prompt that consistently helps your environment, commit it—future you (and your team) will thank you.