- Posted on
- • Artificial Intelligence
Artificial Intelligence Code Reviews for Bash Scripts
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Code Reviews for Bash Scripts
Bash runs the world behind the scenes: deploys, backups, cron jobs, CI runners. Yet many teams still treat shell code as “glue” that doesn’t merit real reviews. That’s how quoting bugs, unsafe globs, and brittle pipelines slip into production.
Here’s the good news: AI can triage Bash changes in seconds, spot subtle pitfalls, and explain safer patterns—especially when combined with proven static tools. In this guide, you’ll set up an AI-assisted review loop that’s fast, reproducible, and privacy-conscious.
Why AI code reviews for Bash are worth it
Bash is unforgiving. A missing quote can corrupt data; a silent glob can change meaning across shells.
Static tools (ShellCheck, shfmt) are outstanding, but they don’t always explain tradeoffs or context. AI fills that gap with suggestions and rationale.
Review bandwidth is scarce. AI can do first-pass triage so humans focus on architecture and intent.
Privacy can be preserved. With a local model you can keep scripts and secrets on your machine.
What you’ll build
A pragmatic, layered review workflow:
1) Run static checks (ShellCheck, shfmt, codespell).
2) Ask a local LLM for a plain-English code review focused on correctness and safety.
3) Wire it into a Git hook or CI so reviews are automatic and repeatable.
You’ll get copy-pastable commands, installation steps for apt, dnf, zypper, and ready-to-use Bash snippets.
Install the essentials
Below are distro-specific commands for commonly used tools. Run the set for your system.
Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y shellcheck codespell jq golang-go git curl
Fedora/RHEL (dnf)
sudo dnf install -y ShellCheck codespell jq golang git curl
openSUSE (zypper)
sudo zypper install -y ShellCheck codespell jq go git curl
Install shfmt (via Go)
# Ensure $HOME/go/bin is on your PATH
echo 'export PATH="$HOME/go/bin:$PATH"' >> ~/.bashrc
. ~/.bashrc
# Install latest shfmt
go install mvdan.cc/sh/v3/cmd/shfmt@latest
# Verify
shfmt -version
Optional: Install a local LLM with Ollama
- Keeps your code on your machine, ideal for privacy-conscious reviews.
# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh
# Start the service (if not auto-started)
ollama serve &
# Pull a small, code-capable model (choose one that runs well on your hardware)
ollama pull qwen2.5-coder:7b
# or
ollama pull mistral:latest
# or
ollama pull codellama:7b-instruct
Step 1 — Establish a strong static baseline
Run these checks before asking any AI for help. They’re fast, deterministic, and catch a lot of common pitfalls.
ShellCheck: static analysis with shell-specific insights.
shfmt: consistent formatting to reduce noisy diffs and make AI output more focused.
codespell: find typos in comments, flags, and docs.
Commands you can reuse:
# Analyze all .sh files
find . -type f -name "*.sh" -print0 | xargs -0 shellcheck -S style
# Format in place with common style options
shfmt -w -i 2 -ci -sr .
# Find common spelling mistakes, ignoring .git
codespell -S .git
Pro tip: Fail your CI early on static issues; only then run the heavier AI review.
Step 2 — Give AI the right context (a review prompt that works)
Good prompts = useful, repeatable advice. Provide goals and constraints, not just “review this.”
Save this as .ai/prompt.txt:
You are reviewing Bash scripts for a production Linux environment.
Goals:
- Correctness: quoting, word splitting, globbing, IFS, read -r, pipefail.
- Safety: set -euo pipefail where appropriate, fail-fast, safe tempfiles, no untrusted eval.
- Portability: POSIX vs Bash features called out explicitly.
- Clarity: simpler constructs, functions, comments where intent isn’t obvious.
Output:
- 5–10 concrete, prioritized findings.
- For each: Why it matters, minimal diff or one-liner fix.
- Avoid speculative changes; do not invent missing context.
Step 3 — A tiny Bash tool to run local AI reviews
Create a script tools/ai_review.sh to pipe your prompt and the target script into a local model (via Ollama). Requires jq and ollama.
#!/usr/bin/env bash
set -euo pipefail
MODEL="${MODEL:-qwen2.5-coder:7b}"
PROMPT_FILE="${PROMPT_FILE:-.ai/prompt.txt}"
TARGET="${1:-}"
if [[ -z "${TARGET}" || ! -f "${TARGET}" ]]; then
echo "Usage: $0 path/to/script.sh" >&2
exit 1
fi
# Assemble a single prompt with clear separators
read -r -d '' FULL_PROMPT <<'P'
=== REVIEW INSTRUCTIONS ===
P
FULL_PROMPT+=$'\n'
FULL_PROMPT+="$(cat "$PROMPT_FILE")"
FULL_PROMPT+=$'\n\n'
FULL_PROMPT+="=== FILE UNDER REVIEW: ${TARGET} ==="$'\n'
FULL_PROMPT+="```bash"$'\n'
FULL_PROMPT+="$(cat "$TARGET")"$'\n'
FULL_PROMPT+="```"$'\n'
# Run the model
echo "Running AI review with model: ${MODEL}" >&2
ollama run "${MODEL}" "${FULL_PROMPT}"
Usage:
chmod +x tools/ai_review.sh
MODEL=mistral:latest tools/ai_review.sh ./scripts/backup.sh
If you prefer HTTP and structured responses, you can post to http://localhost:11434/api/generate with curl and parse output with jq.
Step 4 — Make it automatic (Git hook + Makefile)
Hook that runs on commit or push is the best way to keep reviews consistent.
Create .git/hooks/pre-push:
#!/usr/bin/env bash
set -euo pipefail
echo "[pre-push] Static checks…"
find . -type f -name "*.sh" -print0 | xargs -0 shellcheck -S style
shfmt -d -i 2 -ci -sr . # -d = show diff but do not write; fail if there are diffs
codespell -S .git
echo "[pre-push] AI review (changed .sh files)…"
changed=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.sh$' || true)
if [[ -n "${changed}" ]]; then
while IFS= read -r f; do
echo "----- AI review: $f -----"
tools/ai_review.sh "$f" || true
echo
done <<< "${changed}"
else
echo "No shell files staged; skipping AI review."
fi
chmod +x .git/hooks/pre-push
Optional Make targets (add to Makefile):
lint:
find . -type f -name "*.sh" -print0 | xargs -0 shellcheck -S style
shfmt -d -i 2 -ci -sr .
codespell -S .git
fmt:
shfmt -w -i 2 -ci -sr .
Now make lint gives a quick pass; your hook enforces it before pushing.
Step 5 — Real-world example and what AI adds
Bad (common pitfalls):
#!/usr/bin/env bash
backup_dir=/var/backups
for f in $(ls $backup_dir/*.sql); do
gzip -9 $f > $f.gz
done
Static tools will flag:
Useless
lsin command substitution (word splitting + globbing risk).Unquoted expansions (
$backup_dir,$f).Truncation risk with redirection.
Missing
set -euo pipefail.
AI review often suggests a safer rewrite and explains why:
#!/usr/bin/env bash
set -euo pipefail
backup_dir="/var/backups"
shopt -s nullglob
for f in "$backup_dir"/*.sql; do
gzip -9 -- "$f"
done
Uses
shopt -s nullglobto avoid literal pattern when no matches.Quotes expansions and uses
--to end options.Removes useless
ls.Adds fail-fast options and explains tradeoffs (e.g., how
-einteracts with pipelines, suggestingset -o pipefail).
That blend—deterministic lint + contextual explanation—is where AI shines.
Guardrails for safe AI use
Don’t paste secrets, tokens, or proprietary data into remote services. Prefer a local model for internal code.
Treat suggestions as drafts. You own the final changes.
Keep prompts and tools in the repo to make reviews reproducible.
Log model/version used (e.g.,
MODELenv) in CI artifacts.
Troubleshooting
shfmt not found: ensure
$HOME/go/binis on your PATH andgo install …succeeded.Ollama says model not found: run
ollama pull <model>first.ShellCheck finds too many warnings: baseline and fix classes of issues incrementally; you can start with
-S warningand move toward-S style.
Conclusion and next steps
Bash deserves real reviews. With ShellCheck/shfmt/codespell catching the mechanical issues and a local LLM explaining risks and safer patterns, you’ll ship scripts that are more robust, portable, and maintainable.
Your next 30 minutes:
1) Install ShellCheck, shfmt, codespell, and optionally Ollama.
2) Add .ai/prompt.txt and tools/ai_review.sh.
3) Wire up the pre-push hook and run make lint.
If you want a deeper dive, extend the hook to:
Fail on AI-detected “High” severity issues only.
Store AI review output as a CI artifact.
Maintain a “Bash style guide” the AI references for consistent advice.
Ship safer shell.