Posted on
Artificial Intelligence

Artificial Intelligence for Linux Documentation Generation

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

Artificial Intelligence for Linux Documentation Generation: From --help to Polished Docs

You shipped a new flag last night. Today, issues are piling up because the README is outdated and man has nothing to say. Sound familiar? What if your docs updated themselves every time your script changed—drafted by AI, checked by you, and published in minutes?

This post shows how to wire AI into a Bash-friendly pipeline that turns --help, comments, and change logs into solid, repeatable documentation: README, man pages, and examples.

Why AI for docs is worth your time

  • Your CLI already contains the truth. --help, --version, and inline comments are the most reliable sources of intent. AI shines at turning these signals into structured docs.

  • Reproducible and local if you want. You can run everything with a local model (e.g., via Ollama) or a remote OpenAI-compatible endpoint. The rest is plain Bash.

  • Docs drift less. A small script in CI can regenerate drafts on every PR so you’ll only review changes instead of writing from scratch.


1) Make your script doc-friendly

AI can’t invent accurate docs; it refines what you give it. Make your script self-describing:

  • Provide consistent --help and --version

  • Add short, structured comments near options and functions

  • Keep a simple CHANGELOG.md

Example logtrim:

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

VERSION="0.4.0"

print_usage() {
  cat <<'EOF'
logtrim - Trim noisy log files by level and date

Usage:
  logtrim [OPTIONS] [FILE]

Options:
  -l, --level LEVEL   Minimum level to keep (debug|info|warn|error). Default: info
  -b, --before DATE   Drop entries on or after DATE (YYYY-MM-DD)
  -a, --after DATE    Drop entries before DATE (YYYY-MM-DD)
  -o, --out FILE      Write output to FILE (default: stdout)
  -h, --help          Show this help and exit
  -v, --version       Show version and exit

Examples:
  logtrim -l warn /var/log/app.log
  logtrim --after 2024-07-01 --out cleaned.log app.log
EOF
}

if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  print_usage
  exit 0
fi

if [[ "${1:-}" == "--version" || "${1:-}" == "-v" ]]; then
  echo "logtrim ${VERSION}"
  exit 0
fi

## parse_args: Reads CLI flags and validates LEVEL and DATE formats
## filter_logs: Grep/sed pipeline that filters by level and date
# ...implementation...

The comments and --help are the raw materials the model will shape.


2) Install the toolchain

We’ll use only well-known packages. Choose your package manager:

  • apt (Debian/Ubuntu)
sudo apt update
sudo apt install -y jq pandoc help2man curl git
  • dnf (Fedora/RHEL/CentOS Stream)
sudo dnf install -y jq pandoc help2man curl git
  • zypper (openSUSE/SLE)
sudo zypper refresh
sudo zypper install -y jq pandoc help2man curl git

Optional: a local AI runtime (Ollama)

curl -fsSL https://ollama.com/install.sh | sh
# After installation, pull a model (choose one that fits your hardware):
ollama pull llama3
# or a smaller one:
ollama pull mistral

Tip: If you prefer a remote API, set these env vars (for any OpenAI-compatible provider):

export OPENAI_API_KEY="sk-..."
export OPENAI_BASE_URL="https://api.openai.com/v1"   # or your compatible endpoint
export OPENAI_MODEL="gpt-4o-mini"                    # or any supported model

3) Extract source-of-truth into a single context file

Create scripts/gen-doc-context.sh to gather what the model needs:

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

TOOL="${1:-./logtrim}"         # path to your CLI
OUTDIR="${2:-docs}"
mkdir -p "$OUTDIR"

HELP="$("$TOOL" --help 2>&1 || true)"
VER="$("$TOOL" --version 2>&1 || true)"
CHANGELOG="$(test -f CHANGELOG.md && cat CHANGELOG.md || true)"
COMMENTS="$(grep -E '^\s*##|^\s*#\s*TODO' -n "$TOOL" || true)"

cat > "${OUTDIR}/context.md" <<EOF
# Context for Documentation Generation

## Version
$VER

## CLI Help
\`\`\`
$HELP
\`\`\`

## Notable Code Comments
\`\`\`
$COMMENTS
\`\`\`

## Changelog (if present)
$CHANGELOG
EOF

echo "Wrote ${OUTDIR}/context.md"

Run it:

bash scripts/gen-doc-context.sh ./logtrim docs

4) Generate first drafts with AI (local or remote)

Pick one of the two paths below. Both write Markdown you’ll own and edit.

A) Local model via Ollama

PROMPT_FILE=docs/context.md
OUT_README=README.md
OUT_TLDR=docs/tldr.md

ollama run llama3 <<'EOF' | tee "$OUT_README"
You are a technical writer for Linux CLI tools. Based on the following context,
draft a concise, accurate README in Markdown with:

- Title and 1–2 sentence summary

- Installation (script download example)

- Usage with a table of options and default values

- 3–4 realistic examples

- Exit codes, notes, and limitations

- A "Man page" section header (content summarized)

Context:
<<<
EOF
cat "$PROMPT_FILE" >> "$OUT_README"

And a short TL;DR-style page:

cat > docs/tldr_prompt.txt <<'EOF'
Produce a terse TL;DR for the CLI below:

- One-sentence description

- Usage line

- 3–5 common examples
Keep Markdown under ~25 lines. No fluff.

Context:
EOF

(cat docs/tldr_prompt.txt && cat docs/context.md) | \
  ollama run llama3 | tee "$OUT_TLDR"

B) Remote OpenAI-compatible API with curl

PROMPT="$(printf '%s\n' \
"You are a technical writer for Linux CLI tools. Create a README as follows:" \
"- Title + short summary" \
"- Installation" \
"- Usage with options table" \
"- 3–4 examples" \
"- Exit codes, notes, limitations" \
"Context starts after the delimiter." \
"---" \
"$(cat docs/context.md)")"

curl -sS "${OPENAI_BASE_URL}/chat/completions" \
  -H "Authorization: Bearer ${OPENAI_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{
        \"model\": \"${OPENAI_MODEL}\",
        \"messages\": [
          {\"role\": \"system\", \"content\": \"You write accurate, concise CLI documentation.\"},
          {\"role\": \"user\", \"content\": $(jq -Rs . <<< \"$PROMPT\")}
        ],
        \"temperature\": 0.2
      }" | jq -r '.choices[0].message.content' > README.md

Review the drafts. Edit anything that looks off. The AI provides the scaffolding; you remain the source of truth.


5) Build and publish man pages and HTML

You can auto-generate a man page directly from --help with help2man, then fold AI polish into the README/HTML.

  • From --help (baseline, always accurate):
help2man -N -n "Trim noisy log files by level and date" -o man/logtrim.1 ./logtrim
  • From AI Markdown using pandoc:
# Convert README to a man page:
pandoc -s -t man -o man/logtrim.1 README.md

# Also produce HTML docs:
mkdir -p public
pandoc -s -o public/index.html README.md

Bonus: CI job (GitHub Actions) to keep it evergreen:

# .github/workflows/docs.yml
name: Docs
on:
  push:
    paths: ["logtrim", "CHANGELOG.md", "scripts/**"]
  pull_request:

jobs:
  build-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: sudo apt update && sudo apt install -y jq pandoc help2man curl
      - run: bash scripts/gen-doc-context.sh ./logtrim docs
      # Use Ollama on a self-hosted runner OR a remote API via secrets:
      - env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          OPENAI_BASE_URL: https://api.openai.com/v1
          OPENAI_MODEL: gpt-4o-mini
        run: |
          PROMPT="$(printf '%s\n' "You are a technical writer..." "---" "$(cat docs/context.md)")"
          curl -sS "$OPENAI_BASE_URL/chat/completions" \
            -H "Authorization: Bearer $OPENAI_API_KEY" \
            -H "Content-Type: application/json" \
            -d "{\"model\":\"$OPENAI_MODEL\",\"messages\":[{\"role\":\"system\",\"content\":\"You write accurate, concise CLI documentation.\"},{\"role\":\"user\",\"content\":$(jq -Rs . <<< \"$PROMPT\")}],\"temperature\":0.2}" \
          | jq -r '.choices[0].message.content' > README.md
      - run: |
          mkdir -p man public
          help2man -N -n "Trim noisy log files by level and date" -o man/logtrim.1 ./logtrim || true
          pandoc -s -t man -o man/logtrim.1 README.md
          pandoc -s -o public/index.html README.md
      - uses: actions/upload-artifact@v4
        with:
          name: docs
          path: |
            README.md
            man/logtrim.1
            public/index.html

Real-world workflow in 60 seconds

  • Edit logtrim, update --help.

  • Run:

bash scripts/gen-doc-context.sh ./logtrim docs
ollama run llama3 < docs/context.md > README.md   # or curl to your API
pandoc -s -t man -o man/logtrim.1 README.md
  • Skim the diff, commit, done.

The result:

  • README.md that reflects reality

  • man logtrim that’s always in sync

  • Optional TL;DR and HTML site for users who prefer skimming


Tips for high-quality output

  • Be explicit in --help: default values, formats, examples

  • Keep option names consistent and self-explanatory

  • Add short comments above important functions with inputs/outputs

  • Maintain a lightweight CHANGELOG with one-line entries

  • Keep the AI temperature low (0.1–0.3) for factual tone


Conclusion / Call to Action

Your CLI already knows how it should be documented—AI just helps you say it once and ship it everywhere. Add the scripts above to your repo, wire them into CI, and make doc drift a thing of the past.

Next steps:

  • Install the toolchain with apt/dnf/zypper (see step 2)

  • Add scripts/gen-doc-context.sh

  • Choose local (Ollama) or remote (OpenAI-compatible) generation

  • Build man/HTML with pandoc

  • Review, commit, and iterate

If you want a ready-to-fork example repository with these scripts, say the word and I’ll generate a starter template tailored to your CLI.