Posted on
Artificial Intelligence

Artificial Intelligence Bash Scripts for Home Labs

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Artificial Intelligence Bash Scripts for Home Labs

What if your homelab had a shell-native copilot—one that can read your logs, draft runbooks, and translate your intent into safe commands? With today’s lightweight local LLMs and a few lines of Bash, you can.

In this post you’ll:

  • Stand up a local AI endpoint with zero cost and good privacy

  • Wrap it with a tiny ai.sh Bash function

  • Automate real home-lab tasks (log summaries, daily ops reports, and natural-language-to-Bash with safeguards)

By the end, you’ll have practical scripts you can drop into your /usr/local/bin or repo and start using immediately.


Why AI + Bash is a perfect fit for home labs

  • Bash is the glue of your lab: logs, services, containers, backups, and infra-as-code flow through it.

  • LLMs are great at synthesis and explanation: “What’s going on in these 500 lines of logs?” is their sweet spot.

  • Local-first is finally practical: Models like Llama 3 8B run on a modest box, and privacy stays on your network.

  • HTTP everywhere: Most LLMs expose a simple JSON API, so curl and jq are all you need.


0) Prerequisites (apt, dnf, zypper)

We’ll use curl, jq, and a container engine (Podman or Docker) to host a local model.

  • Ubuntu/Debian (apt):
sudo apt update && sudo apt install -y curl jq podman
  • Fedora/RHEL/CentOS Stream (dnf):
sudo dnf install -y curl jq podman
  • openSUSE Leap/Tumbleweed (zypper):
sudo zypper refresh
sudo zypper install -y curl jq podman

Docker alternative (optional):

  • Ubuntu/Debian: https://docs.docker.com/engine/install/ubuntu/

  • Fedora/openSUSE: https://docs.docker.com/engine/install/


1) Stand up a local LLM endpoint (Ollama)

Option A — Container (works across distros, uses Podman by default):

# Start Ollama
podman run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama --restart=always docker.io/ollama/ollama:latest

# Pull a small, capable model
podman exec -it ollama ollama pull llama3:8b

Using Docker instead:

docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama --restart=unless-stopped ollama/ollama:latest
docker exec -it ollama ollama pull llama3:8b

Option B — Native install script:

curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3:8b

Environment defaults (optional, add these to your shell profile):

echo 'export AI_PROVIDER=ollama' >> ~/.bashrc
echo 'export AI_MODEL=llama3:8b' >> ~/.bashrc
echo 'export OLLAMA_HOST=http://localhost:11434' >> ~/.bashrc
source ~/.bashrc

Cloud API (optional): If you also want to use an OpenAI-compatible API, set:

echo 'export AI_PROVIDER=openai' >> ~/.bashrc
echo 'export OPENAI_API_KEY=sk-REPLACE_ME' >> ~/.bashrc
echo 'export OPENAI_BASE_URL=https://api.openai.com/v1' >> ~/.bashrc
echo 'export AI_MODEL=gpt-4o-mini' >> ~/.bashrc
source ~/.bashrc

2) Create a tiny Bash client: ai.sh

This wrapper lets you swap between local (Ollama) and cloud (OpenAI-compatible) with environment variables.

#!/usr/bin/env bash
set -euo pipefail

MODEL="${AI_MODEL:-llama3:8b}"
PROVIDER="${AI_PROVIDER:-ollama}" # ollama or openai
PROMPT=""

while getopts "p:m:" opt; do
  case "$opt" in
    p) PROMPT="$OPTARG" ;;
    m) MODEL="$OPTARG" ;;
  esac
done

: "${PROMPT:?Use -p 'your prompt' }"

if [[ "$PROVIDER" == "ollama" ]]; then
  HOST="${OLLAMA_HOST:-http://localhost:11434}"
  curl -sS -X POST "$HOST/api/generate" \
    -H 'Content-Type: application/json' \
    -d "$(jq -nc --arg model "$MODEL" --arg prompt "$PROMPT" '{model:$model, prompt:$prompt, stream:false}')" \
  | jq -r '.response'
else
  BASE="${OPENAI_BASE_URL:-https://api.openai.com/v1}"
  KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY for provider=openai}"
  curl -sS "$BASE/chat/completions" \
    -H "Authorization: Bearer $KEY" \
    -H "Content-Type: application/json" \
    -d "$(jq -nc --arg model "$MODEL" --arg prompt "$PROMPT" '{model:$model, messages:[{role:"user", content:$prompt}], temperature:0.2}')" \
  | jq -r '.choices[0].message.content'
fi

Usage:

chmod +x ai.sh
./ai.sh -p "In 3 bullets, explain why journald is useful in a homelab."

3) Real-world example: Summarize and triage service logs

Turn noisy logs into an actionable brief. Example for nginx:

#!/usr/bin/env bash
set -euo pipefail
SERVICE="${1:-nginx}"
LINES="${2:-500}"

LOG="$(journalctl -u "$SERVICE" -n "$LINES" --no-pager || true)"

./ai.sh -p "You are a Linux SRE. Summarize the following $SERVICE logs.

- Highlight errors/warnings and counts

- Identify likely root causes

- Suggest exact next commands to verify/fix
Keep it concise and practical.

LOG START
$LOG
LOG END"

Run it:

chmod +x summarize-logs.sh
./summarize-logs.sh nginx 800

Try with other services:

./summarize-logs.sh docker
./summarize-logs.sh ssh

Tip: Cron a daily digest for a few critical services.


4) Natural language to Bash—safely

Let AI propose a command, show you the rationale, and only run it if you confirm. This reduces copy/paste errors and keeps control with you.

#!/usr/bin/env bash
set -euo pipefail
QUERY="${*:?Usage: $0 <describe what you want to do>}"

PROMPT=$(cat <<'EOF'
You are a strict Bash assistant on Linux. Output ONLY valid JSON with keys:

- cmd: a single safe, POSIX-compatible command line (no pipes to curl|sh)

- explanation: one-paragraph rationale

- dangerous: true if the command mutates system state or deletes data.
Never include backticks or extra text.
EOF
)

JSON="$(./ai.sh -p "$PROMPT

Task: $QUERY")"

CMD="$(jq -r '.cmd' <<<"$JSON")"
EXPL="$(jq -r '.explanation' <<<"$JSON")"
DANGER="$(jq -r '.dangerous' <<<"$JSON" 2>/dev/null || echo false)"

echo "Proposed command:"
echo "  $CMD"
echo
echo "Why:"
echo "  $EXPL"
echo
if [[ "$DANGER" == "true" ]]; then
  echo "Note: This command may change system state."
fi
read -rp "Run it now? (y/N) " ans
if [[ "${ans:-N}" =~ ^[Yy]$ ]]; then
  eval "$CMD"
else
  echo "Aborted."
fi

Examples:

./nl2bash.sh "list docker images sorted by size descending"
./nl2bash.sh "find the 10 largest files under /var/log and show sizes"
./nl2bash.sh "restart nginx gracefully"

Safety tip: Always read the proposed command. Treat AI like a junior admin—smart, but you’re the final check.


5) Daily homelab health report

Snapshot the system and let AI produce a brief you can skim with coffee.

#!/usr/bin/env bash
set -euo pipefail

SNAPSHOT=$(
  {
    echo "# Host: $(hostname)  Date: $(date -Is)"
    echo "## Disk"
    df -hT | sed 's/^/    /'
    echo "## Containers (Docker/Podman)"
    if command -v docker >/dev/null; then docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'; fi
    if command -v podman >/dev/null; then podman ps --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'; fi
    echo "## Failed systemd units"
    systemctl --failed || true
    echo "## Recent syslog (last 300 lines)"
    journalctl -n 300 --no-pager || true
  } | sed $'s/\r//'
)

./ai.sh -p "You are on-call for a homelab. From the snapshot below, produce:

- A one-paragraph health summary

- Top 3 risks with concrete evidence

- Actionable next steps for the next 24h
Limit to ~200 words.

SNAPSHOT
$SNAPSHOT"

Schedule it (example cron at 08:00 daily; adjust path and output handling as you like):

(crontab -l 2>/dev/null; echo "0 8 * * * /opt/homelab/daily-report.sh >> /opt/homelab/reports/$(hostname)-$(date +\%Y\%m).log") | crontab -

Tips, performance, and troubleshooting

  • Model choice: llama3:8b is a good default. On CPUs with 16+ GB RAM you’ll get usable speed; a GPU helps but isn’t required for small models.

  • Security: Don’t auto-run AI-generated commands. Keep the confirmation prompt, and consider running risky commands in containers or test VMs first.

  • Streaming: For a live “typing” effect, remove stream:false and parse lines; start simple first.

  • API switching: Set AI_PROVIDER and AI_MODEL per script or per session to hop between local and cloud.

  • SELinux/AppArmor: If the container can’t write its volume, check security contexts and container engine logs.


Conclusion and next steps (CTA)

You now have:

  • A local AI endpoint (Ollama) running on your homelab

  • A generic ai.sh that turns any prompt into an answer right in your terminal

  • Three practical automations: log triage, safe NL→Bash, and a daily health report

Next steps:

  • Drop these scripts into a git repo for your lab

  • Add service-specific prompts (e.g., for Kubernetes, Proxmox, NAS)

  • Experiment with different models and prompts for your workflows

If this saved you time, adapt the scripts to your environment and share your favorite prompts or improvements. Your homelab just got a lot smarter—right from Bash.