Posted on
Artificial Intelligence

Artificial Intelligence Bash Automation for Daily Linux Tasks

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

Artificial Intelligence Bash Automation for Daily Linux Tasks

Stop copy-pasting the same shell one-liners every morning. Imagine asking your terminal: “Clean up large files in my home directory, but don’t delete anything—just show me what’s safe.” And getting a vetted command, an explanation, and even a daily system health report—all automated.

This post shows how to plug modern AI into your Bash workflow to save time, reduce mistakes, and learn as you go—without abandoning the command line you already love.

Why AI + Bash is worth your time

  • Natural language to shell: Turn “find large files and sort them” into a safe, single command with a confirmation step.

  • Summarize noise: Compress long logs and diffs into clear action items.

  • Learn faster: Ask AI to explain a gnarly one-liner before you run it.

  • Keep it private if needed: Use local models (e.g., Ollama) to avoid sending sensitive data to the cloud.

The result: less context-switching, fewer copy-paste errors, and a smarter terminal session that scales with your day.

Prerequisites (install with your package manager)

We’ll use only common, well-supported CLI tools.

  • curl

  • jq

  • git (for the commit message helper)

Install with apt (Debian/Ubuntu):

sudo apt update
sudo apt install -y curl jq git

Install with dnf (Fedora/RHEL/CentOS Stream):

sudo dnf install -y curl jq git

Install with zypper (openSUSE):

sudo zypper refresh
sudo zypper install -y curl jq git

Optional: Run AI locally with Ollama (avoids cloud APIs):

curl -fsSL https://ollama.com/install.sh | sh
# Example: pull a small, efficient model
ollama pull llama3:8b

Note: The Ollama install script auto-detects your distro. See their docs for details and alternatives.

Minimal setup (cloud or local)

Export environment variables in your shell profile (e.g., ~/.bashrc) depending on your provider.

Using a cloud API (example: OpenAI):

export OPENAI_API_KEY="sk-...your key..."
export OPENAI_MODEL="gpt-4o-mini"    # or another chat-capable model

Using a local model via Ollama:

export OLLAMA_MODEL="llama3:8b"
# Optional: set OLLAMA_HOST if running remotely
# export OLLAMA_HOST="http://localhost:11434"

Reload your shell after editing:

source ~/.bashrc

Drop-in AI helpers for Bash

Save the following script as ~/bin/ai.sh and make it executable:

chmod +x ~/bin/ai.sh

Then source it from ~/.bashrc:

# at the end of ~/.bashrc
source "$HOME/bin/ai.sh"

Here’s the script:

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

# Provider-agnostic AI call. Uses OpenAI if OPENAI_API_KEY is set; otherwise tries Ollama.
_ai_call() {
  local system_msg="${1:-"You are a helpful assistant."}"
  local user_msg="${2:-""}"

  if [[ -n "${OPENAI_API_KEY:-}" ]]; then
    local model="${OPENAI_MODEL:-gpt-4o-mini}"

    # Build JSON payload safely with jq
    local payload
    payload="$(jq -n \
      --arg model "$model" \
      --arg sys "$system_msg" \
      --arg user "$user_msg" \
      '{
        model: $model,
        messages: [
          {role: "system", content: $sys},
          {role: "user", content: $user}
        ],
        temperature: 0
      }'
    )"

    curl -fsS https://api.openai.com/v1/chat/completions \
      -H "Authorization: Bearer ${OPENAI_API_KEY}" \
      -H "Content-Type: application/json" \
      -d "$payload" \
      | jq -r '.choices[0].message.content' \
      | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
    return
  fi

  if command -v ollama >/dev/null 2>&1; then
    local model="${OLLAMA_MODEL:-llama3:8b}"
    # Concatenate system and user for a simple prompt with Ollama
    ollama run "$model" "$system_msg

$user_msg" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
    return
  fi

  echo "No AI provider configured. Set OPENAI_API_KEY or install Ollama." >&2
  return 1
}

# 1) Natural language to safe shell command (with confirmation)
aicmd() {
  if [[ $# -eq 0 ]]; then
    echo "Usage: aicmd <what you want to do in plain English>" >&2
    return 2
  fi
  local request="$*"
  local sys="You translate plain English into a single, safe Bash command.
Rules:

- Output ONLY the command, no explanations.

- Prefer read-only or dry-run flags when possible.

- Never use destructive ops (no rm -rf /, no :(){:|:&};:, etc.).

- If the task is ambiguous, choose the safer interpretation."
  local cmd
  cmd="$(_ai_call "$sys" "$request")" || return 1

  # Strip code fences if model added them
  cmd="$(printf '%s' "$cmd" | sed -E 's/^```(bash)?//; s/```$//')"
  echo "Proposed command:"
  echo "  $cmd"
  read -rp "Run it? [y/N] " ans
  if [[ "${ans:-N}" =~ ^[Yy]$ ]]; then
    echo "Executing..."
    bash -c "$cmd"
  else
    echo "Aborted."
  fi
}

# 2) Summarize and prioritize from stdin (logs, outputs, etc.)
aisum() {
  local topic="${1:-"Summarize the input focusing on key issues and actionable next steps."}"
  if ! [ -t 0 ]; then
    # Piped input
    local input
    input="$(cat)"
    _ai_call "You summarize technical logs and outputs concisely with bullets and priorities." "$topic

Input:
$input"
  else
    echo "Usage: <command producing text> | aisum [topic]" >&2
    return 2
  fi
}

# 3) Generate a Conventional Commit-style message from staged changes
aigcommit() {
  if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Not a git repository." >&2
    return 1
  fi
  if [[ -z "$(git diff --staged)" ]]; then
    echo "No staged changes. Use: git add -A (or specific files) then re-run." >&2
    return 2
  fi

  local diff
  # Limit size to avoid token overflows
  diff="$(git diff --staged | head -n 2000)"

  local sys="You write concise Conventional Commit messages (e.g., feat:, fix:, docs:, chore:).

- Use imperative mood

- Keep subject <= 72 chars

- Add short body only if helpful

- No code fences"
  local msg
  msg="$(_ai_call "$sys" "Generate a commit message for these staged changes:

$diff")" || return 1

  echo "Proposed commit message:"
  echo
  echo "$msg"
  echo
  read -rp "Use this message? [y/N] " ans
  if [[ "${ans:-N}" =~ ^[Yy]$ ]]; then
    git commit -m "$msg"
  else
    echo "Aborted."
  fi
}

# 4) Daily system health report (for cron)
aireport() {
  local rpt_dir="${HOME}/.local/share/ai-reports"
  mkdir -p "$rpt_dir"

  # Collect lightweight snapshots
  local snapshot
  snapshot="$(
    echo "Date: $(date -Is)"
    echo
    echo "Disk usage (df -h):"
    df -h | sed 's/^/  /'
    echo
    echo "Top processes (top -b -n1 | head -n 20):"
    top -b -n1 | head -n 20 | sed 's/^/  /'
    echo
    echo "Memory (free -h):"
    free -h | sed 's/^/  /'
    echo
    echo "Services failed (systemctl --failed):"
    systemctl --failed || true
    echo
    echo "Recent errors (journalctl -p 3 -n 200 --no-pager):"
    journalctl -p 3 -n 200 --no-pager 2>/dev/null || true
  )"

  local sys="You are a Linux SRE co-pilot. Produce a short Markdown health report:

- Bullet lists with priorities (High/Med/Low)

- Specific, safe remediation steps

- Keep it under ~200 lines

- If all good, say so"
  local summary
  summary="$(_ai_call "$sys" "$snapshot")" || return 1

  local out="${rpt_dir}/sysreport-$(date +%F).md"
  printf "%s\n\n---\nGenerated: %s\n" "$summary" "$(date -Is)" > "$out"
  echo "Wrote: $out"
}

Pro tip: open a new shell or source ~/bin/ai.sh to load functions.

4 real-world automations you can use today

1) Natural-language to safe command

  • Example:
aicmd find the 10 largest files in my home folder but do not delete anything
  • You’ll get a proposed one-liner (e.g., a du/find pipeline), review it, and confirm before it runs.

2) Log triage on demand

  • Example:
journalctl -u ssh -n 500 --no-pager | aisum "Identify repeated errors and likely root causes"
  • Great for noisy services. Pipe any command output into aisum to get a digest with next steps.

3) AI-generated commit messages

  • Example:
git add -A
aigcommit
  • Produces a Conventional Commit-style message from staged changes, with a confirmation step.

4) Daily health report with cron

  • Add a daily job at 9 AM:
crontab -e
  • Then add:
0 9 * * * /usr/bin/env bash -lc 'source "$HOME/bin/ai.sh" && aireport' >> "$HOME/.local/share/ai-reports/cron.log" 2>&1
  • Check your reports at:
ls ~/.local/share/ai-reports/*.md

Security, privacy, and reliability tips

  • Don’t auto-execute model output. aicmd asks for confirmation by design.

  • Keep API keys secret (env vars, not in scripts; consider a .env file with 600 perms).

  • Scrub sensitive data before sending to cloud LLMs. Prefer local models (Ollama) for logs that may contain secrets.

  • Rate limits and cost: summarize smaller chunks (tail -n 400) and set temperature low.

  • Version your helpers (git) and review diffs like any other code.

Conclusion and next steps

You don’t need to rewrite your workflow to get real value from AI in the terminal. Start with one helper—like aicmd or aisum—then add a daily aireport once you’re comfortable. From there, expand prompts and tailor the scripts to your stack.

Call to action:

  • Install curl, jq, and git with your package manager (apt/dnf/zypper).

  • Add the ai.sh helpers to your shell.

  • Try one task you do every day and see how much time you save.

If you build a neat prompt or helper, share it with your team—or turn it into a dotfiles snippet others can reuse. Happy automating!