- Posted on
- • Artificial Intelligence
Artificial Intelligence Linux Automation Templates
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Linux Automation Templates: Make Bash Do More With Less
If you’ve ever stared at a messy log, fumbled for the perfect commit message, or wished a second pair of eyes would sanity‑check a risky command, you’re not alone. AI can now slot into tiny Unixy scripts to shave minutes (and mistakes) off your day—without turning your workstation into a science project.
This article gives you drop‑in Bash templates that wire AI into your workflow. You’ll get working examples, installation instructions for apt, dnf and zypper, and pragmatic guidance on when to use cloud APIs vs. local models.
Why this matters
Reuse your existing tools. These are plain Bash + curl + jq snippets that compose with git, cron, and systemd.
Keep control. Use a local LLM for privacy, or a cloud API when you need quality or speed.
Automate real toil. Summarize logs, improve commit messages, explain risky commands, and auto‑draft docs—without leaving the terminal.
Prerequisites
The templates use curl, jq, and git. Install them with your package manager:
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y curl jq gitFedora/RHEL/CentOS Stream (dnf):
sudo dnf install -y curl jq gitopenSUSE (zypper):
sudo zypper refresh sudo zypper install -y curl jq git
For scheduled jobs you can use cron (or systemd timers). To install and enable cron:
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y cron sudo systemctl enable --now cronFedora/RHEL/CentOS Stream (dnf) uses cronie:
sudo dnf install -y cronie sudo systemctl enable --now crondopenSUSE (zypper):
sudo zypper install -y cron sudo systemctl enable --now cron
Pick your AI backend: cloud or local
Choose one, or configure both and switch with an env var.
Cloud API (example: OpenAI):
- Export an API key:
export OPENAI_API_KEY="your_key" - Uses HTTPS; good quality/latency; be mindful of cost and data sensitivity.
- Export an API key:
Local model (example: Ollama + Llama 3 family):
- Install Ollama:
curl -fsSL https://ollama.com/install.sh | sh- Pull a model (adjust to your hardware):
ollama pull llama3- Runs at http://localhost:11434; keeps data on your machine.
One-time: minimal AI helper config
Create a tiny helper env and function you can source in templates.
~/.config/ai/ai.env:
# Backend: "openai" or "ollama"
export AI_PROVIDER="${AI_PROVIDER:-ollama}"
# Cloud settings (set your key in your shell profile, not here)
export OPENAI_API_KEY="${OPENAI_API_KEY:-}"
export OPENAI_MODEL="${OPENAI_MODEL:-gpt-4o-mini}"
export OPENAI_URL="${OPENAI_URL:-https://api.openai.com/v1/chat/completions}"
# Local settings
export OLLAMA_MODEL="${OLLAMA_MODEL:-llama3}"
export OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434/api/chat}"
# A concise, task-focused system prompt you can reuse
export AI_SYSTEM_PROMPT="${AI_SYSTEM_PROMPT:-You are a terse Linux assistant. Prefer bullet points and concrete commands.}"
~/.config/ai/ai.sh:
#!/usr/bin/env bash
set -euo pipefail
AI_ENV="${AI_ENV:-$HOME/.config/ai/ai.env}"
[ -f "$AI_ENV" ] && # shellcheck disable=SC1090
. "$AI_ENV"
ai_chat() {
# Usage: ai_chat "Your prompt" > output.txt
local prompt="${1:-}"
if [[ -z "$prompt" ]]; then
echo "ai_chat: empty prompt" >&2
return 1
fi
if [[ "${AI_PROVIDER:-}" == "openai" ]]; then
if [[ -z "${OPENAI_API_KEY:-}" ]]; then
echo "OPENAI_API_KEY is not set" >&2
return 1
fi
jq -n --arg sys "$AI_SYSTEM_PROMPT" --arg usr "$prompt" --arg model "${OPENAI_MODEL:-gpt-4o-mini}" '
{model:$model, messages:[{role:"system",content:$sys},{role:"user",content:$usr}], temperature:0.2}
' | curl -fsS "$OPENAI_URL" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- | jq -r '.choices[0].message.content'
else
jq -n --arg sys "$AI_SYSTEM_PROMPT" --arg usr "$prompt" --arg model "${OLLAMA_MODEL:-llama3}" '
{model:$model, messages:[{role:"system",content:$sys},{role:"user",content:$usr}], options:{temperature:0.2}}
' | curl -fsS "$OLLAMA_URL" \
-H "Content-Type: application/json" \
-d @- | jq -r '.message.content'
fi
}
Make it executable:
chmod +x ~/.config/ai/ai.sh
Tip: Add . ~/.config/ai/ai.env to your shell profile to make the vars available in new sessions.
Template 1: Zero-friction AI commit messages (git hook)
Generate high-quality, conventional commit messages from staged diffs. Keeps you moving and improves your history.
.git/hooks/prepare-commit-msg:
#!/usr/bin/env bash
set -euo pipefail
HOOK_MSG_FILE="$1"
HOOK_SOURCE="${2:-}"
HOOK_SHA="${3:-}"
# Skip if commit message already provided (e.g., merge commits)
if [[ -s "$HOOK_MSG_FILE" && "${HOOK_SOURCE:-}" != "commit" ]]; then
exit 0
fi
# Load AI helper
# shellcheck disable=SC1090
. "$HOME/.config/ai/ai.sh"
diff="$(git diff --staged)"
if [[ -z "$diff" ]]; then
exit 0
fi
prompt=$(cat <<'EOF'
Write a concise conventional commit message for the following staged diff.
Rules:
- Type one of: feat, fix, refactor, docs, test, chore, perf, ci, build.
- Max 72-char subject; optional short body lines if needed.
- Mention scopes if obvious (e.g., bash, ci, docs).
Diff:
EOF
)
msg="$(ai_chat "$prompt"$'\n'"$diff")" || exit 0
# Only write if hook file is empty or auto-generated
if [[ ! -s "$HOOK_MSG_FILE" ]]; then
printf "%s\n" "$msg" > "$HOOK_MSG_FILE"
fi
Enable the hook:
chmod +x .git/hooks/prepare-commit-msg
Switch providers on the fly:
AI_PROVIDER=ollama git commit
AI_PROVIDER=openai git commit
Template 2: Nightly log summarizer with cron
Have AI skim service logs and mail or save a digest. Great for personal servers or side projects.
~/bin/ai-log-summary:
#!/usr/bin/env bash
set -euo pipefail
SERVICE="${1:-sshd}"
SINCE="${SINCE:-12 hours ago}"
OUT="${OUT:-$HOME/log-summaries/${SERVICE}-$(date +%F).md}"
mkdir -p "$(dirname "$OUT")"
# Load AI helper
# shellcheck disable=SC1090
. "$HOME/.config/ai/ai.sh"
# Collect logs (journald example)
logs="$(journalctl -u "$SERVICE" --since "$SINCE" --no-pager || true)"
# Basic redaction of emails, tokens, IPv4 (customize for your org)
redacted="$(printf "%s" "$logs" \
| sed -E 's/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+/[redacted@email]/g' \
| sed -E 's/[A-Fa-f0-9]{32,}/[redacted_token]/g' \
| sed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/[redacted_ip]/g'
)"
prompt=$(cat <<'EOF'
Summarize these logs for a busy Linux operator:
- Bullet key incidents, errors, and anomalies
- Group by theme with counts
- Propose 2–3 actionable next steps
- Keep under 200 lines
Logs:
EOF
)
summary="$(ai_chat "$prompt"$'\n'"$redacted")"
printf "%s\n" "# $(date -Is) — $SERVICE log summary" > "$OUT"
printf "\n%s\n" "$summary" >> "$OUT"
echo "Wrote $OUT"
Make it executable:
chmod +x ~/bin/ai-log-summary
Add a cron job to run at 23:30 daily:
crontab -e
Then add:
30 23 * * * SINCE="24 hours ago" OUT="$HOME/log-summaries/sshd-$(date +\%F).md" $HOME/bin/ai-log-summary sshd
Ensure cron is installed and running (see installation section above). For journald-less setups, swap journalctl with tail -n 5000 /var/log/your.log.
Template 3: “Explain before you run” command helper
Ask AI to describe what a command will do and potential foot‑guns before you press Enter.
~/bin/ai-explain:
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -eq 0 ]]; then
echo "Usage: ai-explain <command...>" >&2
exit 1
fi
# Load AI helper
# shellcheck disable=SC1090
. "$HOME/.config/ai/ai.sh"
cmd="$*"
prompt=$(cat <<EOF
Explain, step-by-step, what this shell command is likely to do, including potential risks.
Command:
$cmd
Format:
- One-line summary
- Steps (bullet list)
- Risks (bullet list), call out destructive flags
- Safer alternative if relevant
EOF
)
ai_chat "$prompt"
Usage:
ai-explain 'rsync -av --delete ~/src/ user@server:/srv/src/'
Note: Always treat the explanation as advice, not authority. If it looks wrong, test in a scratch directory or add --dry-run when available.
Template 4: Auto-draft READMEs for your shell scripts
Turn terse comments into decent documentation for each script in a repo.
~/bin/ai-docs-sh:
#!/usr/bin/env bash
set -euo pipefail
DIR="${1:-.}"
OUT="${OUT:-README.autogen.md}"
# Load AI helper
# shellcheck disable=SC1090
. "$HOME/.config/ai/ai.sh"
# Collect scripts
mapfile -t scripts < <(find "$DIR" -maxdepth 1 -type f -name "*.sh" | sort)
if [[ ${#scripts[@]} -eq 0 ]]; then
echo "No .sh files in $DIR" >&2
exit 0
fi
bundle=""
for f in "${scripts[@]}"; do
name="$(basename "$f")"
shead="$(awk 'NR<=80{print}' "$f")"
bundle+=$'\n'"--- $name ---"$'\n'"$shead"$'\n'
done
prompt=$(cat <<'EOF'
You are generating concise documentation for a set of Bash scripts.
For each script:
- Show a one-line purpose
- Show usage (flags/args) inferred from comments and getopts
- Provide 1–2 realistic examples
- Call out environment variables the script reads
- Keep it accurate and brief
Scripts (name and first ~80 lines each):
EOF
)
doc="$(ai_chat "$prompt"$'\n'"$bundle")"
printf "%s\n" "$doc" > "$OUT"
echo "Wrote $OUT"
Run it:
cd ~/projects/your-repo
~/bin/ai-docs-sh .
Commit the generated README as a starting point, then refine by hand.
Practical tips and guardrails
Keep secrets out of prompts. Redact tokens, emails, and IPs as shown, or add stricter filters.
Start local when in doubt. Ollama is great for privacy and prototyping; switch to a cloud API when you need better summaries or faster turnaround.
Cap prompt sizes. Logs can be huge; sample recent lines or summarize chunks first.
Make cost visible. If using a paid API, wrap
ai_chatwith counters or budget caps.Version your prompts. Store them next to scripts so improvements are trackable in git.
Conclusion and next steps
You don’t need a platform rewrite to get value from AI. A few tiny Bash templates can smooth your daily workflow right now:
Drop in the git hook for better commit messages
Schedule the log summarizer to keep tabs on services
Use ai-explain before risky commands
Auto-draft docs for your scripts
Pick one template, install the prerequisites with your package manager, and ship it today. Then iterate: tune prompts, swap models, and grow your toolkit as you discover new friction to remove.