- Posted on
- • Artificial Intelligence
Advanced Artificial Intelligence Bash Techniques
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Advanced Artificial Intelligence Bash Techniques: Supercharge Your Terminal
If you’ve ever stared at a cryptic error, waded through megabytes of logs, or spent 10 minutes crafting the perfect sed one‑liner, you’ve felt the friction of the command line. Now imagine the shell that explains itself, drafts commands for you, and summarizes noisy output on demand. This post shows how to infuse Bash with advanced AI techniques—directly from the terminal—using simple functions and standard tools.
You’ll get:
Why AI belongs in your Bash workflow today
3–5 actionable, production‑ready patterns you can drop into
~/.bashrcInstructions to install required tools on apt, dnf, and zypper systems
Real examples you can try in under 10 minutes
Why AI + Bash is a valid, valuable pairing
Speed: The shell already excels at quick iteration. AI closes the loop even further—explain errors, propose fixes, and draft commands without switching context.
Breadth: Logs, JSON, YAML, CLI docs, repos—your terminal touches it all. AI can summarize, transform, and search these text streams in place.
Safety and control: Keep your workflow transparent. You decide what leaves your host, you redact secrets, and you can run fully local models if you prefer.
Prerequisites and installation
We’ll rely on widely available CLI tools. Install as needed.
Required:
curl (HTTP requests)
jq (JSON parsing)
git (for the commit-message example)
Optional:
A cloud LLM API key (e.g., OPENAI_API_KEY) or
A local model runtime (Ollama)
Install the basics:
Debian/Ubuntu (apt):
sudo apt update && sudo apt install -y curl jq gitFedora/RHEL (dnf):
sudo dnf install -y curl jq gitopenSUSE (zypper):
sudo zypper refresh && sudo zypper install -y curl jq git
Optional local models via Ollama (cross‑distro installer):
curl -fsSL https://ollama.com/install.sh | sh
# After installing, you can pull a model (example):
ollama pull llama3
Note: Ollama isn’t typically packaged in default apt/dnf/zypper repos; the official installer above handles setup.
Environment variables for cloud use:
export OPENAI_API_KEY="sk-...your key..."
Core technique: a drop‑in ai Bash function
This single function gives you a consistent way to talk to either a cloud LLM or a local Ollama model. Add it to ~/.bashrc (or ~/.bash_profile), then source it.
# ~/.bashrc (or similar)
# ai: send a prompt to either OpenAI (cloud) or Ollama (local).
# Usage:
# ai "explain exit code 137"
# echo "summarize this text" | ai
# Options:
# -m MODEL (default: gpt-3.5-turbo for OpenAI, llama3 for Ollama)
# -s SYSTEM_MSG (system prompt, optional)
# -t TEMP (temperature, default 0.2)
ai() {
local MODEL="" SYSTEM="" TEMP="0.2"
while getopts ":m:s:t:" opt; do
case $opt in
m) MODEL="$OPTARG" ;;
s) SYSTEM="$OPTARG" ;;
t) TEMP="$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
# Read prompt either from args or stdin
local PROMPT
if [ $# -gt 0 ]; then
PROMPT="$*"
else
PROMPT="$(cat)"
fi
# Prefer local Ollama if running; otherwise use OpenAI if key is set.
if curl -sS http://localhost:11434/api/tags >/dev/null 2>&1; then
# Ollama path (no streaming)
local OMODEL="${MODEL:-llama3}"
curl -sS http://localhost:11434/api/generate \
-H "Content-Type: application/json" \
-d "$(jq -n --arg m "$OMODEL" --arg sys "$SYSTEM" --arg p "$PROMPT" \
'{model:$m, prompt:($sys|length>0 ? ($sys+"\n\n"+$p) : $p), stream:false}')" \
| jq -r '.response'
elif [ -n "$OPENAI_API_KEY" ]; then
# OpenAI path (Chat Completions)
local OMODEL="${MODEL:-gpt-3.5-turbo}"
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer '"$OPENAI_API_KEY"'" \
-d "$(jq -n --arg m "$OMODEL" --arg sys "$SYSTEM" --arg p "$PROMPT" --argjson t "$TEMP" \
'{
model:$m,
messages: ([($sys|length>0) as $hasSys | if $hasSys then {role:"system",content:$sys} else empty end] + [{role:"user",content:$p}]),
temperature: ($t|tonumber)
}')" \
| jq -r '.choices[0].message.content'
else
echo "ai: No backend available. Start Ollama (localhost:11434) or set OPENAI_API_KEY." >&2
return 1
fi
}
Test it:
ai -s "Be concise." "Explain 'permission denied' when writing to /etc/hosts and how to fix."
Technique 1: AI error explainer and autofix suggester
Tired of deciphering errors? Wrap any command with fix to get a plain‑English explanation plus a suggested fix. It only asks AI on failure.
# Run a command; on nonzero exit, ask AI to explain and suggest a safer fix.
fix() {
if [ $# -eq 0 ]; then
echo "Usage: fix <command ...>" >&2
return 2
fi
local TMP_ERR
TMP_ERR="$(mktemp)"
# Run the command, capturing stderr while preserving stdout/stderr behavior
"$@" 2> >(tee "$TMP_ERR" >&2)
local RC=$?
if [ $RC -ne 0 ]; then
# Optional redaction to avoid leaking secrets
# export REDACT_PATTERN='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{20,})'
local ERR_TXT
if [ -n "$REDACT_PATTERN" ]; then
ERR_TXT="$(sed -E "s/${REDACT_PATTERN}/[REDACTED]/g" "$TMP_ERR")"
else
ERR_TXT="$(cat "$TMP_ERR")"
fi
echo
echo "---- AI diagnosis (exit $RC) ----"
printf "%s\n" "$ERR_TXT" | ai -s "You are a Bash assistant. Explain the error succinctly, then propose a minimal, safe fix. Provide a corrected command if applicable."
fi
rm -f "$TMP_ERR"
return $RC
}
Example:
fix cp file.txt /root/
If it fails with “Permission denied,” you’ll get a short explanation and a safer alternative, e.g., “Use sudo: sudo cp file.txt /root/” plus a note about risks.
Technique 2: One‑liner log summarizer
When log floods make your eyes glaze over, summarize the last N lines with context. Works for files, journalctl, docker logs, etc.
# Summarize the tail of a log with optional keyword and time window hints.
logsum() {
local FILE="$1"; shift || true
local N="${1:-200}" # default to last 200 lines
if [ -z "$FILE" ] || [ ! -r "$FILE" ]; then
echo "Usage: logsum /path/to/log [lines]" >&2
return 2
fi
tail -n "$N" -- "$FILE" \
| ai -s "You are an SRE log assistant. Summarize key issues, error clusters, timestamps, and likely root causes. Be concise and actionable."
}
Example:
sudo journalctl -u nginx --since "1 hour ago" | tee /tmp/nginx.log >/dev/null
logsum /tmp/nginx.log 400
Tip: For JSON logs, pre‑normalize with jq, e.g.:
jq -r '[.ts, .level, .msg] | @tsv' /var/log/myapp.json | ai -s "Summarize recurring errors and their probable causes."
Technique 3: Safer AI command generator with confirmation
Let AI draft the command, but you stay in control. This function asks for a task, renders the exact command only (no prose), shows you, and runs it only if you confirm.
# Ask AI to produce ONLY a single safe shell command for the requested task.
ask() {
if [ $# -eq 0 ]; then
echo "Usage: ask \"describe the task\"" >&2
return 2
fi
local REQ="$*"
local CMD
CMD="$(ai -s "Output ONLY a single POSIX-compatible shell command without explanations. Use safe defaults (no -rf, no destructive ops) unless explicitly asked. If ambiguity exists, choose the least destructive option." "$REQ")"
echo "Proposed command:"
echo " $CMD"
read -r -p "Run it? [y/N] " ans
case "$ans" in
y|Y) eval "$CMD" ;;
*) echo "Aborted." ;;
esac
}
Examples:
ask "find and count all .log files under /var that changed in the last 24 hours"
ask "download https://example.com/data.csv to ~/Downloads and show the first 5 lines"
Technique 4: AI‑assisted Git commit messages
Automate high‑quality commit messages from staged changes. This hook drafts a Conventional Commit‑style summary you can edit.
1) Make a helper that summarizes your diff:
git_ai_commit() {
local DIFF
DIFF="$(git diff --cached)"
if [ -z "$DIFF" ]; then
echo "No staged changes." >&2
return 1
fi
ai -s "Write a concise Conventional Commit message (type: feat/fix/docs/refactor/test/chore).
Explain what changed and why in 1 subject line (<= 72 chars) and an optional short body. Use present tense, no trailing period on subject." \
"Staged diff:
$DIFF"
}
2) Optional: integrate as a prepare-commit-msg hook:
# .git/hooks/prepare-commit-msg (make executable)
#!/usr/bin/env bash
set -euo pipefail
MSG_FILE="$1"
# Skip if message already provided (e.g., merge)
if [ -s "$MSG_FILE" ]; then
exit 0
fi
if ! command -v ai >/dev/null 2>&1; then
exit 0
fi
SUGGESTION="$(git_ai_commit || true)"
if [ -n "$SUGGESTION" ]; then
printf "%s\n\n# AI suggestion below. Edit as needed.\n%s\n" "$SUGGESTION" "$(date)" > "$MSG_FILE"
fi
Result: git commit opens with a high‑quality starting point you can tweak.
Good practices: security, cost, and control
Redact secrets: Set
REDACT_PATTERNinfixor pre‑filter logs (e.g.,sed -E 's/([A-Za-z0-9_]{20,})/[REDACTED]/g').Keep it small: Tail or sample logs before sending to AI to control latency and cost.
Prefer local when needed: If data sensitivity is high, use Ollama locally.
Be explicit: Use system prompts to enforce “concise,” “single command only,” or “no destructive operations.”
Putting it together
Copy the
ai,fix,logsum, andaskfunctions into your shell profile.Verify your backend: start Ollama or export OPENAI_API_KEY.
Try one pattern today: wrap your next failing command with
fix, or generate your nextgitmessage withgit_ai_commit.
Your terminal is already the most powerful UI on your machine. With a few Bash functions and an AI backend, it becomes collaborative, explanatory, and faster. Start with one technique, iterate, and share what you automate next.