Posted on
Artificial Intelligence

Automating Daily Linux Tasks with Artificial Intelligence

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

Automating Daily Linux Tasks with Artificial Intelligence

If you can explain a task in plain English, you’re five minutes away from automating it. That’s the promise of pairing Bash with modern AI. Instead of hand-crafting brittle scripts for every edge case, you can have a small, auditable Bash wrapper ask a local or cloud model to draft commands, summarize logs, triage files, and suggest maintenance steps—then you decide whether to run them. The result: less toil, more time for deep work, and automations that evolve as your needs change.

This post shows why AI belongs in your Linux toolbox and gives you 4 practical, copy‑pasteable examples you can deploy today.


Why use AI for Linux automation?

  • Natural language becomes a control surface: Describe the outcome you want; get a candidate command or plan back.

  • Faster iteration with less boilerplate: Let the model rough in the steps; you keep final review and control.

  • Stronger guardrails with “propose-then-confirm”: Keep “human in the loop” to prevent surprises.

  • Local-first is viable: With tools like Ollama you can run competent models entirely on your machine, no data leaves your box.


Prerequisites and installation

You can use a local LLM (recommended) or a cloud API. We’ll make our scripts auto-detect what you have.

Core utilities used below:

  • curl

  • jq

  • inotify-tools (for directory watching)

  • cron or systemd timers (for scheduling; most systems have systemd already)

Install the basics with your package manager:

  • Debian/Ubuntu (apt):

    • sudo apt update && sudo apt install -y curl jq inotify-tools cron
    • Enable cron: sudo systemctl enable --now cron
  • Fedora/RHEL/CentOS Stream (dnf):

    • sudo dnf install -y curl jq inotify-tools cronie
    • Enable cron: sudo systemctl enable --now crond
  • openSUSE (zypper):

    • sudo zypper install -y curl jq inotify-tools cron
    • Enable cron: sudo systemctl enable --now cron

Choose one AI backend:

Option A — Local model with Ollama (no external API):

  • Install:

    • curl -fsSL https://ollama.com/install.sh | sh
  • Get a compact, capable model (example):

    • ollama pull llama3.1
  • Test:

    • echo "Say hello from Bash" | ollama run llama3.1

Option B — Cloud API via shell-gpt (OpenAI, etc.):

  • Install pipx if you don’t have it:

    • apt: sudo apt install -y pipx && pipx ensurepath
    • dnf: sudo dnf install -y pipx && pipx ensurepath
    • zypper: sudo zypper install -y pipx && pipx ensurepath
    • Fallback if pipx package is unavailable:
    • python3 -m pip install --user pipx && python3 -m pipx ensurepath
  • Install shell-gpt:

    • pipx install shell-gpt
  • Set your API key:

    • export OPENAI_API_KEY="sk-..." (put this in your shell profile)

We’ll write our scripts to use Ollama if present, else shell-gpt if present, else exit with a helpful message.


Reusable helper: one function for talking to your model

Put this in ~/.bashrc (or source it from a ~/bin/ai-common.sh file):

# Simple LLM wrapper: prefers Ollama, falls back to shell-gpt (sgpt).
# Usage: llm "your prompt"
llm() {
  local prompt="$1"
  local model="${AI_MODEL:-llama3.1}"

  if command -v ollama >/dev/null 2>&1; then
    # Ollama local, no network
    ollama run "$model" -p "$prompt"
  elif command -v sgpt >/dev/null 2>&1; then
    # shell-gpt (cloud) - requires OPENAI_API_KEY
    sgpt --model "${AI_MODEL:-gpt-4o-mini}" "$prompt"
  else
    echo "No AI backend found. Install Ollama or shell-gpt (sgpt)." >&2
    return 1
  fi
}

Reload your shell: source ~/.bashrc

You can set a model explicitly per session:

  • Local: export AI_MODEL=llama3.1

  • Cloud: export AI_MODEL=gpt-4o-mini (or your preferred model)


1) Safe AI-assisted command runner (propose → review → execute)

Turn natural language into a proposed Bash command, then confirm before it runs.

Create ~/bin/ai-cmd and make it executable:

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

# Source llm() if kept in another file:
# source "$HOME/bin/ai-common.sh"

if ! declare -f llm >/dev/null; then
  echo "llm() function not found. Add it to your shell or source it here." >&2
  exit 1
fi

if [[ $# -eq 0 ]]; then
  echo "Usage: ai-cmd \"Describe what you want the command to do\"" >&2
  exit 1
fi

TASK="$*"

PROMPT=$(cat <<'EOF'
You are a cautious Linux shell expert. Return a single safe Bash command that:

- Solves the user's task

- Uses -print/--dry-run or echoes actions where possible

- NEVER uses rm -rf without an explicit path and a dry-run preview

- Avoids destructive actions unless the user asked for them explicitly

- Includes comments inline (using && echo steps) if multi-part
Only output the command, nothing else.
EOF
)

CMD="$(llm "$PROMPT

User task:
$TASK
")" || { echo "LLM failed"; exit 1; }

echo
echo "Proposed command:"
echo "------------------------------------------------------------"
echo "$CMD"
echo "------------------------------------------------------------"
read -rp "Run this command? [y/N] " ans
if [[ "${ans,,}" == "y" ]]; then
  eval "$CMD"
else
  echo "Aborted."
fi

Example:

  • ai-cmd "find and delete node_modules directories older than 30 days under ~/work, but show a preview first"

Why it works:

  • You get speed without surrendering control.

  • The prompt encodes guardrails (dry-runs, no blind deletes).


2) Daily log digest: AI summarizes what mattered

Have the system collect the last 24 hours of noteworthy logs and summarize them into a brief report you can skim with coffee.

Script ~/bin/ai-log-digest:

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

if ! declare -f llm >/dev/null; then
  echo "llm() not found. Source it before running." >&2
  exit 1
fi

OUT_DIR="${HOME}/ai-digests"
mkdir -p "$OUT_DIR"
TS="$(date +'%Y-%m-%d')"
OUT_FILE="${OUT_DIR}/digest-${TS}.md"

collect_logs() {
  if command -v journalctl >/dev/null 2>&1; then
    # Systemd journal: last 24h, higher priority messages
    journalctl --since "24 hours ago" -p 0..4 -o short-iso 2>/dev/null || true
  elif [[ -f /var/log/syslog ]]; then
    # Syslog fallback (Debian/Ubuntu)
    awk -v d="$(date -d 'yesterday' '+%b %_d')" '
      BEGIN { start=0 }
      { print }
    ' /var/log/syslog 2>/dev/null || true
  else
    echo "No recognizable logs on this system." >&2
  fi
}

LOGS="$(collect_logs | tail -n 5000)"

SUMMARY="$(llm "Summarize the following system logs from the last 24 hours.

- Group by service/component

- Highlight errors/warnings and likely root causes

- Suggest 3 concrete next steps with commands where possible

- Keep it under 300 words

Logs:
$LOGS
")"

{
  echo "# Daily System Digest ($TS)"
  echo
  echo "Generated on: $(date -Iseconds)"
  echo
  echo "## Summary"
  echo
  echo "$SUMMARY"
} > "$OUT_FILE"

echo "Wrote: $OUT_FILE"

Make it executable: chmod +x ~/bin/ai-log-digest

Schedule it (choose one):

  • Cron (system-wide):

    • crontab -e and add:
    • 15 7 * * * /home/youruser/bin/ai-log-digest
  • Systemd timer (user):

    • ~/.config/systemd/user/ai-log-digest.service:
    [Unit]
    Description=AI Daily Log Digest
    
    [Service]
    Type=oneshot
    ExecStart=/home/youruser/bin/ai-log-digest
    
    • ~/.config/systemd/user/ai-log-digest.timer:
    [Unit]
    Description=Run AI Daily Log Digest every morning
    
    [Timer]
    OnCalendar=07:15
    Persistent=true
    
    [Install]
    WantedBy=timers.target
    
    • Enable:
    • systemctl --user daemon-reload
    • systemctl --user enable --now ai-log-digest.timer

3) Auto-classify and file new downloads

Watch your Downloads folder; when a new file appears, ask the model to categorize it and move it into a tidy directory structure.

Install inotify-tools (if you haven’t yet):

  • apt: sudo apt install -y inotify-tools

  • dnf: sudo dnf install -y inotify-tools

  • zypper: sudo zypper install -y inotify-tools

Script ~/bin/ai-file-sorter:

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

WATCH_DIR="${1:-$HOME/Downloads}"
DEST_DIR="${DEST_DIR:-$HOME/Library}"
CATEGORIES=("invoices" "media" "ebooks" "archives" "code" "images" "misc")

if ! declare -f llm >/dev/null; then
  echo "llm() not found. Source it before running." >&2
  exit 1
fi

mkdir -p "$DEST_DIR"
for c in "${CATEGORIES[@]}"; do mkdir -p "$DEST_DIR/$c"; done

classify() {
  local fpath="$1"
  local fname="$(basename "$fpath")"
  local prompt="Choose the single best category for this file name from: ${CATEGORIES[*]}.
Return only the category, nothing else.

File: $fname"
  llm "$prompt" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'
}

echo "Watching: $WATCH_DIR"
inotifywait -m -e close_write -e moved_to --format '%w%f' "$WATCH_DIR" | while read -r file; do
  [[ -f "$file" ]] || continue
  cat_hint=""
  cat_hint="$(classify "$file" || echo misc)"
  # Fallback if model returns an unknown label
  dest_cat="misc"
  for c in "${CATEGORIES[@]}"; do
    if [[ "$cat_hint" == "$c" ]]; then dest_cat="$c"; break; fi
  done
  echo "→ $file → $DEST_DIR/$dest_cat/"
  mv -n -- "$file" "$DEST_DIR/$dest_cat/" || echo "Skip (exists?): $file"
done

Run it in a terminal:

  • chmod +x ~/bin/ai-file-sorter

  • ai-file-sorter or ai-file-sorter /path/to/watch

Tip:

  • Add logic to extract text from PDFs before classifying (e.g., pdftotext) if you want content-aware sorting. Remember to install poppler-utils:
    • apt: sudo apt install -y poppler-utils
    • dnf: sudo dnf install -y poppler-utils
    • zypper: sudo zypper install -y poppler-tools

4) AI-assisted maintenance checklist and recommendations

Collect key system stats, then ask the model to suggest prioritized actions with commands.

Script ~/bin/ai-healthcheck:

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

if ! declare -f llm >/dev/null; then
  echo "llm() not found. Source it before running." >&2
  exit 1
fi

detect_pm() {
  if command -v apt >/dev/null 2>&1; then echo "apt"
  elif command -v dnf >/dev/null 2>&1; then echo "dnf"
  elif command -v zypper >/dev/null 2>&1; then echo "zypper"
  else echo "unknown"; fi
}

updates() {
  case "$(detect_pm)" in
    apt) apt -qq update >/dev/null 2>&1 || true; apt -qq list --upgradable 2>/dev/null || true ;;
    dnf) dnf -q check-update || true ;;
    zypper) zypper -q lu || true ;;
    *) echo "Package manager not detected." ;;
  esac
}

REPORT="$(mktemp)"
{
  echo "=== Disk usage (df -h) ==="
  df -h
  echo
  echo "=== Memory (free -h) ==="
  free -h
  echo
  echo "=== Top processes (top -b -n1 | head -n 20) ==="
  top -b -n1 | head -n 20
  echo
  echo "=== Failed services (systemctl --failed) ==="
  systemctl --failed || true
  echo
  echo "=== Pending updates ==="
  updates
} > "$REPORT"

PLAN="$(llm "Given the following Linux system snapshot, produce a concise maintenance plan:

- Prioritize by urgency (P1..P3)

- Include exact commands for each step

- Note any services that should be restarted

- Keep under 250 words

Snapshot:
$(cat "$REPORT")
")"

echo "===== AI Maintenance Plan ====="
echo "$PLAN"
rm -f "$REPORT"

Run it:

  • chmod +x ~/bin/ai-healthcheck

  • ai-healthcheck

Optionally schedule it weekly via cron or a systemd timer similar to the log digest.


Real-world tips

  • Keep prompts opinionated: encode guardrails like “return only one command” or “prefer dry-run.”

  • Log everything: Have automations write to ~/ai-logs/ so you can audit later.

  • Start read-only: Grep, list, summarize. Add writes/moves/deletes only after you’re confident.

  • Prefer local for privacy: Ollama lets you keep logs and prompts on your machine.

  • Version your scripts: Put ~/bin under git and add small changes over time.


Conclusion and next step (CTA)

AI won’t replace your shell skills—it multiplies them. Start with one automation: 1) Install Ollama or shell-gpt. 2) Drop in the llm() helper. 3) Pick a script above—ai-cmd is a great first step. 4) Run it, review the result, then schedule it.

Once it saves you ten minutes a day, add the next one. Your future self will thank you.