- Posted on
- • Artificial Intelligence
Artificial Intelligence Command Line Workflows
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Command Line Workflows: Supercharge Your Bash
The terminal is where real work happens: logs flow, builds run, and ops fires get put out. But there’s a gap—translating natural-language problems into precise commands, making sense of noisy logs, and documenting changes takes time. AI can close that gap right inside your shell.
This guide shows you practical, bash-first workflows for using AI from the command line—without leaving your tmux pane. You’ll get ready-to-paste functions, real-world examples, and both cloud and local model options. By the end, you’ll be summarizing logs, generating git commit messages, explaining scripts, and producing safe command one‑liners with AI—directly from your terminal.
Why AI on the CLI?
It’s composable: pipe anything into a model and pipe the result onward.
It’s reproducible: save prompts as scripts; version them just like code.
It’s secure on your terms: choose local models (no data leaves your machine) or cloud with selective redaction.
It’s fast at scale: batch process many files, logs, or diffs in seconds.
Prerequisites and Installation
You’ll need a handful of CLI tools. Install them with your distro’s package manager.
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y curl jq ripgrep fzf bat git # On Debian/Ubuntu the 'bat' binary may be named 'batcat': command -v bat >/dev/null || echo "alias bat=batcat" >> ~/.bashrcFedora/RHEL/CentOS Stream (dnf):
sudo dnf install -y curl jq ripgrep fzf bat gitopenSUSE (zypper):
sudo zypper refresh sudo zypper install -y curl jq ripgrep fzf bat git
Optional: local LLMs with Ollama (Linux install script; not via apt/dnf/zypper):
curl -fsSL https://ollama.com/install.sh | sh
# Pull a model (examples: llama3, mistral, neural-chat)
ollama pull llama3
One tiny function to talk to AI
Drop this in your ~/.bashrc or ~/.bash_profile and reload your shell. It supports either a cloud endpoint (OpenAI-compatible) or a local Ollama model.
# AI model selection:
# - Cloud: set OPENAI_API_KEY and optionally OPENAI_BASE_URL (default: https://api.openai.com/v1)
# - Local: set OLLAMA_MODEL (e.g., llama3); no API key required
# - Default cloud model can be overridden via AI_MODEL
ai() {
local model="${AI_MODEL:-gpt-4o-mini}"
local prompt input
if [ -t 0 ]; then
prompt="$*"
else
input="$(cat)"
prompt="${*}\n\nINPUT:\n${input}"
fi
if [ -n "${OLLAMA_MODEL:-}" ]; then
# Local inference via Ollama
ollama run "$OLLAMA_MODEL" <<EOF
${prompt}
EOF
return $?
fi
if [ -z "${OPENAI_API_KEY:-}" ]; then
echo "Set OPENAI_API_KEY (cloud) or OLLAMA_MODEL (local) first." >&2
return 1
fi
echo -n "$prompt" | jq -Rs --arg m "$model" '
{
model: $m,
messages: [ {role:"user", content: .} ],
temperature: 0.2,
stream: false
}
' | curl -sS -X POST "${OPENAI_BASE_URL:-https://api.openai.com/v1}/chat/completions" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-H "Content-Type: application/json" \
-d @- \
| jq -r '.choices[0].message.content'
}
Set your environment to use it:
Cloud (OpenAI-compatible):
export OPENAI_API_KEY="sk-...yourkey..." # Optional: use another OpenAI-compatible provider # export OPENAI_BASE_URL="https://openrouter.ai/api/v1" export AI_MODEL="gpt-4o-mini" # or gpt-4o, gpt-3.5-turbo, etc.Local via Ollama:
export OLLAMA_MODEL="llama3"
Persist those exports by adding them to your ~/.bashrc.
Tip: redact secrets before piping to AI:
scrub() { sed -E 's/(Authorization: Bearer )[^" ]+/\1***REDACTED***/g; s/(password=)[^& ]+/\1REDACTED/g'; }
4 AI Workflows You Can Use Today
1) Summarize and triage logs in seconds
Triage errors:
rg -n -i 'error|warn|fail' /var/log/*.log \ | ai "Group similar errors, identify likely root causes, and propose the top 3 fixes."Condense service churn:
journalctl -u ssh --since "today" --no-pager \ | ai "Summarize notable events and anomalies. Provide bullet points + quick remediation checklist."Create a morning ops digest:
{ echo "NGINX (last 1h):"; journalctl -u nginx --since "1 hour ago" --no-pager echo; echo "Systemd (last 1h):"; journalctl --since "1 hour ago" -p warning --no-pager } \ | ai "Produce a concise report with sections, counts, and prioritized actions. Keep under 200 words."
Why it’s useful: you keep context in the terminal, get a quick read on pattern-of-life issues, and act faster.
2) Turn natural language into safe one‑liners
Ask for commands without memorizing flags. Never auto-run; review first.
Helper to request just a command:
askcmd() { ai "You are a bash assistant. Output only a single POSIX-compatible shell command with safe defaults (no sudo, no destructive actions) for this task: $*" }Examples:
askcmd "Find the 10 largest files under /var excluding /var/log" askcmd "Show top 15 processes by memory with headers" askcmd "Recursively replace foo with bar in .txt files but preview changes first"
Refine with context you care about (e.g., you prefer ripgrep, jq, or fzf).
3) Generate high-quality git commit messages
Consistent, informative commits make diffs and blame kinder. Use AI to propose Conventional Commit style messages from staged changes.
On-demand:
aicm() { local diff diff="$(git diff --staged)" [ -z "$diff" ] && { echo "Nothing staged."; return 1; } ai "Write a concise Conventional Commit message for this diff. - 1 short subject (<= 72 chars) - Optional bullet list body with rationale and risk - No code blocks DIFF: ${diff}" }Auto-suggest via a git hook (prepare-commit-msg):
# .git/hooks/prepare-commit-msg #!/usr/bin/env bash set -euo pipefail msg_file="$1" # If a message already exists (e.g., merge), keep it [ -s "$msg_file" ] && exit 0 diff="$(git diff --staged)" [ -z "$diff" ] && exit 0 suggestion="$(ai "Write a concise Conventional Commit message for this diff: - 1 short subject (<= 72 chars) - Optional bullets with rationale - No code blocks DIFF: ${diff}")" printf "%s\n" "$suggestion" > "$msg_file"Make it executable:
chmod +x .git/hooks/prepare-commit-msg
Bonus: you can keep this local-only with Ollama to avoid sending source out.
4) Explain and refactor shell scripts with guardrails
Pipe any script into AI for an explanation, risk analysis, or a safer rewrite.
Explain what it does and identify risks:
ai "Explain this script step by step. Highlight security risks, destructive operations, set -e/-u usage, and safer alternatives." < ./backup.shPropose a safer rewrite:
ai "Rewrite this script with: - set -euo pipefail - quoted variables, no word splitting - traps for cleanup - clear error messages - no sudo Return only the improved script." < ./backup.shReview cron entries or systemd units:
crontab -l | ai "Spot dangerous patterns, recommend better timing, logging, and failure alerts."
Why it’s useful: instant second pair of eyes without context switching to an IDE.
Cloud vs Local: switching is one export away
Cloud (more capable models, costs money, watch data sensitivity):
export OPENAI_API_KEY="sk-..." export AI_MODEL="gpt-4o-mini" # or your preferred modelLocal (private, offline, free after download, may be slower/weaker):
export OLLAMA_MODEL="llama3" # If not pulled yet: # ollama pull llama3
You can flip between them per-shell or per-script.
Tips for safe and cheap usage
Redact secrets: pipe through
scrubbeforeai.Keep prompts small: cut noise with
rg,sed, ortail -n.Be explicit: tell the model “no code blocks,” “one command,” or “bullet list.”
Cache or commit prompts: keep them in scripts to make results reproducible.
Conclusion and Next Steps
AI belongs in your terminal. With a tiny wrapper and a few patterns, you can summarize logs, draft quality commits, generate safe commands, and review scripts without leaving Bash.
Your next steps:
Install the prerequisites with your package manager.
Add the
aifunction to your shell profile and set either OPENAI_API_KEY or OLLAMA_MODEL.Try one workflow today—log triage or commit messages—and iterate.
If you found this useful, drop your best prompt or function into your dotfiles repo, share it with your team, and keep a running library of AI-on-CLI workflows. The shell has always been about composability; AI just added a new pipe.