- Posted on
- • Artificial Intelligence
Learning Artificial Intelligence Automation
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Learning AI Automation for Linux Bash: A Practical Starter Guide
You already automate with Bash: log rotation, cron jobs, backups, one-liners that tame chaos. Now imagine those scripts could read, summarize, and reason about your logs, generate safe shell commands on demand, and write status reports your team actually reads. That’s the promise of AI automation for Linux — adding natural‑language intelligence to the reliable tooling you already use.
In this post you’ll:
Understand why AI + Bash is a natural fit.
Set up a small, reusable ai() helper that calls an OpenAI‑compatible API (cloud or local).
Run 3–5 actionable examples: summarize logs, generate safe commands, produce structured JSON for decisions, and draft commit messages.
Leave with a checklist and next steps to ship your first AI‑powered automation.
Why this matters (and why now)
AI doesn’t replace your scripts — it augments them. Think “a smarter subcommand” that can read, summarize, draft, and suggest.
The interface is just HTTP+JSON. That means Bash + curl + jq is already enough.
You can choose cloud models for accuracy or run local models for privacy and cost control using containers.
What you’ll build
A portable ai() Bash function that takes prompts or stdin and returns model output.
A local AI backend (optional) using Podman + Ollama containers, or a cloud OpenAI‑compatible endpoint.
Scripts you can drop into cron, CI, or your dotfiles.
Install prerequisites
The examples use curl, jq, Python (optional), Git (optional), and Podman (for the local model option). Install with your package manager:
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y curl jq python3 python3-pip git podman
# Optional for scheduled jobs:
sudo apt install -y cron
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y curl jq python3 python3-pip git podman
# Optional for scheduled jobs:
sudo dnf install -y cronie
- openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y curl jq python3 python3-pip git podman
# Optional for scheduled jobs:
sudo zypper install -y cronie
Note: cron is “cron” on Debian/Ubuntu and “cronie” on Fedora/RHEL/openSUSE.
Choose your model backend
You have two good options. You can switch any time by just changing environment variables.
Option A: Cloud or any OpenAI‑compatible API
Set your endpoint, model, and key:
export OPENAI_BASE_URL="https://api.openai.com/v1"
export OPENAI_MODEL="gpt-4o-mini" # or another model your provider offers
export OPENAI_API_KEY="YOUR_API_KEY_HERE"
This also works with any OpenAI‑compatible provider. Consult your provider for the model name and base URL.
Option B: Local model with Podman + Ollama (no internet required)
Run Ollama in a rootless container and pull a small model:
# Start Ollama as a container
podman run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama:latest
# Pull a compact model (example: Meta Llama 3.1 8B variant) inside the container
podman exec -it ollama ollama pull llama3.1
# Point your client to the local OpenAI-compatible endpoint
export OPENAI_BASE_URL="http://localhost:11434/v1"
export OPENAI_MODEL="llama3.1"
# If your client requires a key, set a dummy one:
export OPENAI_API_KEY="ollama"
Test the endpoint:
curl -sS "$OPENAI_BASE_URL/models" | jq
You should see the local model listed.
A tiny ai() function for Bash
Drop this into your ~/.bashrc or a project-local script. It accepts a prompt as an argument or reads from stdin if piped.
ai() {
local input
if [ ! -t 0 ]; then
input="$(cat)"
else
input="$*"
fi
local sys="${AI_SYSTEM_PROMPT:-You are a concise Linux assistant. Answer clearly.}"
local model="${OPENAI_MODEL:-llama3.1}"
local url="${OPENAI_BASE_URL:-http://localhost:11434/v1}"
local key="${OPENAI_API_KEY:-}"
curl -sS -X POST "$url/chat/completions" \
-H "Content-Type: application/json" \
${key:+-H "Authorization: Bearer $key"} \
-d "$(jq -n --arg model "$model" --arg sys "$sys" --arg user "$input" \
'{model:$model, temperature:0.2, stream:false,
messages:[{role:"system",content:$sys},{role:"user",content:$user}] }')" \
| jq -r '.choices[0].message.content'
}
Reload your shell:
source ~/.bashrc
Tip: You can override defaults per-call by exporting OPENAI_BASE_URL, OPENAI_MODEL, AI_SYSTEM_PROMPT, or OPENAI_API_KEY.
4 real-world examples you can run today
1) Summarize recent logs and call out likely causes
Summarize the last 500 syslog lines:
tail -n 500 /var/log/syslog 2>/dev/null | ai "Summarize these syslog lines in 5–10 bullets. Include timestamps, error counts, and likely root causes (disk, memory, DNS, auth). Suggest next steps."
On systems using journalctl:
journalctl -n 500 -p 4..7 | ai "Summarize these logs in bullets with error counts and likely causes. Suggest 3 actionable next steps."
Why it helps: Triage time drops. You get a high-level picture immediately, then drill into specifics.
2) Generate a safe shell command (with confirmation)
This helper asks the model for structured JSON. You review before running.
ai_cmd() {
local task="$*"
local spec='You are a cautious shell assistant. Output ONLY valid JSON with keys: cmd (string), explain (string), danger (boolean). Never include placeholders; use safe defaults (dry-run flags if possible).'
local out
out="$(ai "$spec Task: $task")" || return 1
echo "$out" | jq . || { echo "Model did not return valid JSON"; return 1; }
local cmd explain danger
cmd="$(echo "$out" | jq -r '.cmd // empty')"
explain="$(echo "$out" | jq -r '.explain // empty')"
danger="$(echo "$out" | jq -r '.danger // false')"
echo
echo "Explanation:"
echo "$explain"
echo
echo "Proposed command:"
echo "$cmd"
echo
if [ "$danger" = "true" ]; then
echo "WARNING: The model marked this as potentially dangerous."
fi
read -r -p "Run this command? [y/N] " ans
if [ "$ans" = "y" ] && [ -n "$cmd" ]; then
eval "$cmd"
else
echo "Aborted."
fi
}
Example usage:
ai_cmd "Find and compress large log files older than 14 days under /var/log without deleting originals."
Why it helps: You get a suggested one‑liner plus an explanation and a safety gate before execution.
3) Structured JSON from logs for automation decisions
Turn unstructured logs into structured data your scripts can branch on.
journalctl -p 3 -b | ai "Read these high-priority logs and return strict JSON: {\"severity\":\"low|medium|high\",\"top_causes\":[\"...\"],\"next_steps\":[\"...\"]}. No extra text." \
| tee /tmp/triage.json
sev="$(jq -r '.severity' /tmp/triage.json 2>/dev/null || echo unknown)"
if [ "$sev" = "high" ]; then
echo "[ALERT] High severity issues detected"
printf "Causes:\n"
jq -r '.top_causes[]' /tmp/triage.json
printf "Next steps:\n"
jq -r '.next_steps[]' /tmp/triage.json
# Hook: page, open ticket, or escalate
fi
Why it helps: Your existing shell logic can make decisions based on AI‑extracted JSON without humans in the loop.
4) Draft a Conventional Commit message from staged changes
Speed up clean commits while keeping human review.
git diff --staged | ai "Write a Conventional Commit subject and short body for these changes. Use present tense, <=72 char subject, include scope if obvious. Output subject first line, then blank line, then body."
If you like the output, paste it into:
git commit -F <(git diff --staged | ai "Write a Conventional Commit subject and body...")
Why it helps: Consistent, descriptive commits with less friction.
Safety, cost, and reliability tips
Never eval blindly. Use the ai_cmd JSON‑and‑confirm pattern.
Prefer local models for private data. Use Podman + Ollama to keep logs on‑box.
Keep prompts short and specific. Ask for JSON when you need structure.
Cache expensive calls if you’ll reuse outputs (e.g., save summaries to files with timestamps).
Log inputs/outputs for audit when running in CI/cron (but scrub secrets).
Troubleshooting
If ai() prints nothing:
- Check variables: echo "$OPENAI_BASE_URL" "$OPENAI_MODEL"
- Test endpoint: curl -sS "$OPENAI_BASE_URL/models" | jq
- For cloud, ensure OPENAI_API_KEY is set and valid.
If jq complains:
- Confirm jq is installed: jq --version
- The model may have returned non‑JSON; refine the prompt or reduce temperature.
Your next step (CTA)
Pick a backend:
- Cloud: set OPENAI_BASE_URL, OPENAI_MODEL, and OPENAI_API_KEY.
- Local: start the Ollama container and pull a model.
Add the ai() function to your shell.
Try one example today — the log summary or safe command generator.
Wrap the one you like most into a cron job or a Makefile target and share it with your team.
AI becomes most useful when it’s just another tool in your Bash toolbox — composable, scriptable, and boringly reliable. Start small, iterate, and watch your automation level up.