AI Listsby JustOut Today

AI Lists β€Ί AI Scripts

AI Scripts

Tidy, copy-ready scripts and prompts for AI agents and humans: bash, Python, JavaScript, automation, data, web, DevOps.

🟒 Last checked Nov 20, 2026, 12:03 AM PT44 entries43 links verifiedDaily walkthrough · last run Nov 20, 2026, 12:03 AM PT

Every script is original, short and safe by default (dry-run first where it changes things). Each says what it does and how to run it, and has a copy button. The daily walkthrough syntax-checks every script and re-checks every docs link.

Bash (7)

Dated backup of a folder

Language: bash

Creates a timestamped .tar.gz of any folder.

Run: ./backup-dated.sh ~/projects/site ~/backups

bash
#!/usr/bin/env bash
# backup-dated.sh <dir> [dest]  -> dest/<name>-YYYYmmdd-HHMMSS.tar.gz
set -euo pipefail
src="${1:?usage: $0 <dir> [dest]}"; dest="${2:-.}"
mkdir -p "$dest"
stamp="$(date +%Y%m%d-%H%M%S)"
out="$dest/$(basename "$src")-$stamp.tar.gz"
tar -czf "$out" -C "$(dirname "$src")" "$(basename "$src")"
echo "wrote $out ($(du -h "$out" | cut -f1))"
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Find the biggest files

Language: bash

Lists the N largest files under a folder (GNU find).

Run: ./big-files.sh /var/log 20

bash
#!/usr/bin/env bash
# big-files.sh [dir] [count]
set -euo pipefail
dir="${1:-.}"; n="${2:-20}"
find "$dir" -type f -printf '%s\t%p\n' 2>/dev/null \
  | sort -rn | head -n "$n" \
  | awk -F'\t' '{printf "%8.1f MB  %s\n", $1/1048576, $2}'
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Retry with exponential backoff

Language: bash

Re-runs a flaky command up to N times, doubling the wait each time.

Run: ./retry.sh 5 curl -fsS https://example.com

bash
#!/usr/bin/env bash
# retry.sh <attempts> <command...>
set -uo pipefail
max="${1:?usage: $0 <attempts> <command...>}"; shift
delay=1
for ((i = 1; i <= max; i++)); do
  if "$@"; then exit 0; fi
  echo "attempt $i/$max failed; sleeping ${delay}s" >&2
  sleep "$delay"; delay=$((delay * 2))
done
exit 1
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Is a port open?

Language: bash

Checks a TCP port using only bash and coreutils.

Run: ./port-check.sh example.com 443

bash
#!/usr/bin/env bash
# port-check.sh <host> <port> [timeout-seconds]
host="${1:?host}"; port="${2:?port}"; t="${3:-3}"
if timeout "$t" bash -c "</dev/tcp/$host/$port" 2>/dev/null; then
  echo "open   $host:$port"
else
  echo "closed $host:$port"; exit 1
fi
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Remove duplicate lines, keep order

Language: bash

Dedupes a file or stdin without sorting.

Run: ./dedupe.sh urls.txt > unique.txt

bash
#!/usr/bin/env bash
# dedupe.sh [file]  (reads stdin if no file)
awk '!seen[$0]++' "${1:--}"
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Safe file renamer (slugify)

Language: bash

Renames files to lowercase-dashes. Dry-run unless you pass --apply.

Run: ./slugify-names.sh ~/Downloads --apply

bash
#!/usr/bin/env bash
# slugify-names.sh [dir] [--apply]
set -euo pipefail
dir="${1:-.}"; apply="${2:-}"
for f in "$dir"/*; do
  [ -f "$f" ] || continue
  base="$(basename "$f")"
  new="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]' \
        | sed -E 's/[^a-z0-9.]+/-/g; s/-+/-/g; s/^-|-$//g')"
  [ "$base" = "$new" ] && continue
  if [ -e "$dir/$new" ]; then echo "skip (exists): $new"; continue; fi
  if [ "$apply" = "--apply" ]; then mv -- "$f" "$dir/$new"; echo "renamed: $base -> $new"
  else echo "would rename: $base -> $new"; fi
done
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Watch a log for a pattern

Language: bash

Prints timestamped lines matching a regex as they are written.

Run: ./watch-log.sh /var/log/syslog 'error|fail'

bash
#!/usr/bin/env bash
# watch-log.sh <file> <regex>
set -euo pipefail
file="${1:?file}"; pat="${2:?regex}"
tail -Fn0 "$file" | grep --line-buffered -E "$pat" | while IFS= read -r line; do
  printf '[%s] %s\n' "$(date +%T)" "$line"
done
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Python (7)

CSV to JSON

Language: python

Converts a CSV with a header row into a JSON array.

Run: python3 csv2json.py data.csv > data.json

python
#!/usr/bin/env python3
"""csv2json.py input.csv > out.json"""
import csv
import json
import sys

with open(sys.argv[1], newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))
json.dump(rows, sys.stdout, indent=2, ensure_ascii=False)
print()
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Find duplicate files

Language: python

Groups identical files by size, then SHA-256. Read-only.

Run: python3 dupes.py ~/Pictures

python
#!/usr/bin/env python3
"""dupes.py [root] - prints groups of identical files. Deletes nothing."""
import hashlib
import os
import sys
from collections import defaultdict

root = sys.argv[1] if len(sys.argv) > 1 else "."
by_size = defaultdict(list)
for d, _, files in os.walk(root):
    for n in files:
        p = os.path.join(d, n)
        try:
            by_size[os.path.getsize(p)].append(p)
        except OSError:
            pass

def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

for size, paths in by_size.items():
    if size == 0 or len(paths) < 2:
        continue
    groups = defaultdict(list)
    for p in paths:
        groups[sha(p)].append(p)
    for same in groups.values():
        if len(same) > 1:
            print(f"{size} bytes x{len(same)}:")
            for p in same:
                print("  " + p)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

GET JSON with retries (stdlib)

Language: python

Fetches JSON with a timeout, a polite User-Agent and retries.

Run: python3 get_json.py https://api.github.com/repos/python/cpython

python
#!/usr/bin/env python3
"""get_json.py <url> - prints pretty JSON."""
import json
import sys
import time
import urllib.request

def get_json(url, tries=3, timeout=10):
    req = urllib.request.Request(url, headers={"User-Agent": "example-script/1.0", "Accept": "application/json"})
    for i in range(tries):
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.load(r)
        except Exception as e:
            if i == tries - 1:
                raise
            print(f"retry {i + 1}: {e}", file=sys.stderr)
            time.sleep(2 ** i)

print(json.dumps(get_json(sys.argv[1]), indent=2))
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Check required env vars (without printing them)

Language: python

Fails fast if secrets are missing, never echoing their values.

Run: python3 envcheck.py OPENAI_API_KEY DATABASE_URL

python
#!/usr/bin/env python3
"""envcheck.py NAME [NAME...] - exit 1 if any are unset or empty. Values are never printed."""
import os
import sys

missing = [n for n in sys.argv[1:] if not os.environ.get(n)]
for n in sys.argv[1:]:
    print(f"{n}: {'MISSING' if n in missing else 'set'}")
sys.exit(1 if missing else 0)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Rate limiter decorator

Language: python

Limits how often a function (like an API call) can run.

Run: python3 ratelimit.py

python
#!/usr/bin/env python3
"""ratelimit.py - @rate_limited(calls, per_seconds) for API clients."""
import functools
import time
from collections import deque

def rate_limited(calls, per):
    stamps = deque()
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*a, **kw):
            now = time.monotonic()
            while stamps and now - stamps[0] > per:
                stamps.popleft()
            if len(stamps) >= calls:
                time.sleep(per - (now - stamps[0]))
            stamps.append(time.monotonic())
            return fn(*a, **kw)
        return wrapper
    return deco

@rate_limited(calls=2, per=1.0)
def ping(i):
    print(f"{time.strftime('%X')} call {i}")

if __name__ == "__main__":
    for i in range(5):
        ping(i)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Chunk text for RAG

Language: python

Splits text into overlapping word chunks ready for embedding.

Run: python3 chunk.py notes.txt 200 40 > chunks.jsonl

python
#!/usr/bin/env python3
"""chunk.py <file> [words=200] [overlap=40] -> JSON Lines {id, text}"""
import json
import sys

path = sys.argv[1]
size = int(sys.argv[2]) if len(sys.argv) > 2 else 200
overlap = int(sys.argv[3]) if len(sys.argv) > 3 else 40
if overlap >= size:
    sys.exit("overlap must be smaller than chunk size")
words = open(path, encoding="utf-8").read().split()
step = size - overlap
for n, start in enumerate(range(0, max(len(words) - overlap, 1), step)):
    print(json.dumps({"id": n, "text": " ".join(words[start:start + size])}))
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Rough token estimate

Language: python

Estimates tokens (~4 characters each in English) to budget prompts. An estimate, not exact.

Run: python3 tokens.py prompt.txt

python
#!/usr/bin/env python3
"""tokens.py <file> - rough English token estimate (chars/4). Use a real tokenizer for billing."""
import sys

text = open(sys.argv[1], encoding="utf-8").read()
print(f"chars={len(text)} words={len(text.split())} est_tokens~{round(len(text) / 4)}")
Site blocks bots Β· unverified New Docs β†—

JavaScript (5)

Debounce

Language: javascript

Runs a function only after input stops for N ms (search boxes).

Run: Import and wrap your handler: input.addEventListener('input', debounce(search, 250))

javascript
// debounce.js
export function debounce(fn, ms = 250) {
  let t;
  return (...args) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), ms);
  };
}
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

fetch with timeout

Language: javascript

Aborts a fetch that takes too long (browser or Node 18+).

Run: const res = await fetchWithTimeout('https://example.com', {}, 5000)

javascript
// fetch-timeout.js
export async function fetchWithTimeout(url, options = {}, ms = 8000) {
  const res = await fetch(url, { ...options, signal: AbortSignal.timeout(ms) });
  if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
  return res;
}
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Copy-to-clipboard buttons

Language: javascript

Adds a working Copy button to every <pre><code> block.

Run: Include on any page with <script src="copy.js" defer></script>

javascript
// copy.js
document.querySelectorAll("pre > code").forEach((code) => {
  const btn = document.createElement("button");
  btn.type = "button";
  btn.textContent = "Copy";
  btn.addEventListener("click", async () => {
    await navigator.clipboard.writeText(code.innerText);
    btn.textContent = "Copied!";
    setTimeout(() => (btn.textContent = "Copy"), 1500);
  });
  code.parentElement.before(btn);
});
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

localStorage with expiry

Language: javascript

Caches a value in the browser that expires after a set time.

Run: setCached('feed', data, 3600e3); getCached('feed')

javascript
// cache.js
export function setCached(key, value, ttlMs) {
  localStorage.setItem(key, JSON.stringify({ value, exp: Date.now() + ttlMs }));
}
export function getCached(key) {
  const raw = localStorage.getItem(key);
  if (!raw) return null;
  const { value, exp } = JSON.parse(raw);
  if (Date.now() > exp) { localStorage.removeItem(key); return null; }
  return value;
}
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Instant list filter

Language: javascript

Filters list items as you type, no framework.

Run: Add <input id="q"> above a <ul id="list"> and include this script.

javascript
// filter.js
const q = document.getElementById("q");
const items = [...document.querySelectorAll("#list li")];
q.addEventListener("input", () => {
  const term = q.value.trim().toLowerCase();
  for (const li of items) {
    li.hidden = term !== "" && !li.textContent.toLowerCase().includes(term);
  }
});
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Automation (5)

Cron job that can't overlap

Language: bash

A crontab line that skips a run if the last one is still going.

Run: crontab -e, then paste the line (edit the paths).

bash
# m h dom mon dow  command  (runs 6:00 every day; flock -n skips if still running)
0 6 * * * flock -n /tmp/daily-job.lock /home/me/bin/daily-job.sh >> /home/me/logs/daily-job.log 2>&1
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Auto-commit a snapshot if anything changed

Language: bash

Commits a git repo only when files changed. Good for notes and configs.

Run: ./git-snapshot.sh ~/notes

bash
#!/usr/bin/env bash
# git-snapshot.sh [repo]
set -euo pipefail
cd "${1:-.}"
if [ -n "$(git status --porcelain)" ]; then
  git add -A
  git commit -qm "snapshot $(date -Iseconds)"
  echo "committed"
else
  echo "no changes"
fi
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Run a command when a folder changes

Language: bash

Uses inotifywait to react to new or changed files.

Run: ./on-change.sh ./inbox 'echo changed: '

bash
#!/usr/bin/env bash
# on-change.sh <dir> <command-prefix>   (needs inotify-tools)
set -euo pipefail
dir="${1:?dir}"; cmd="${2:?command}"
inotifywait -m -e close_write,moved_to --format '%w%f' "$dir" | while IFS= read -r path; do
  $cmd "$path"
done
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Post to a webhook

Language: bash

Sends a JSON message to a webhook URL kept in an env var.

Run: WEBHOOK_URL=... ./notify.sh 'Backup finished'

bash
#!/usr/bin/env bash
# notify.sh <message>   (WEBHOOK_URL must be set; never hard-code it)
set -euo pipefail
: "${WEBHOOK_URL:?set WEBHOOK_URL}"
msg="${1:?message}"
payload="$(python3 -c 'import json,sys; print(json.dumps({"text": sys.argv[1]}))' "$msg")"
curl -fsS -X POST -H 'Content-Type: application/json' -d "$payload" "$WEBHOOK_URL" >/dev/null
echo "sent"
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

systemd timer instead of cron

Language: ini

A service + timer pair that runs a script daily and logs to the journal.

Run: Save both files in ~/.config/systemd/user/, then: systemctl --user enable --now daily-job.timer

ini
# ~/.config/systemd/user/daily-job.service
[Unit]
Description=Daily job

[Service]
Type=oneshot
ExecStart=%h/bin/daily-job.sh

# ~/.config/systemd/user/daily-job.timer
[Unit]
Description=Run daily-job every morning

[Timer]
OnCalendar=*-*-* 06:00:00
Persistent=true

[Install]
WantedBy=timers.target
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Data (5)

Load a CSV into SQLite

Language: python

Creates a SQLite table from any CSV so you can query it with SQL.

Run: python3 csv2sqlite.py sales.csv sales.db sales

python
#!/usr/bin/env python3
"""csv2sqlite.py <csv> <db> <table>"""
import csv
import sqlite3
import sys

src, db, table = sys.argv[1:4]
with open(src, newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    cols = ", ".join(f'"{h}"' for h in header)
    marks = ", ".join("?" for _ in header)
    con = sqlite3.connect(db)
    con.execute(f'CREATE TABLE IF NOT EXISTS "{table}" ({cols})')
    con.executemany(f'INSERT INTO "{table}" VALUES ({marks})', reader)
    con.commit()
    print(con.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()[0], "rows")
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

jq one-liners for JSON lists

Language: bash

Turn a JSON array into CSV, count by a field, or filter.

Run: Run each line in a shell with jq installed.

bash
#!/usr/bin/env bash
# Assumes data.json is an array of objects with name, url, category.
jq -r '.[] | [.name, .url] | @csv' data.json                      # to CSV
jq 'group_by(.category) | map({category: .[0].category, n: length})' data.json  # counts
jq '[.[] | select(.category == "Coding")]' data.json             # filter
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Validate a JSON Lines file

Language: python

Reports the line number of any bad JSON line.

Run: python3 jsonl_check.py data.jsonl

python
#!/usr/bin/env python3
"""jsonl_check.py <file> - exit 1 on the first invalid line."""
import json
import sys

bad = 0
with open(sys.argv[1], encoding="utf-8") as f:
    for n, line in enumerate(f, 1):
        if not line.strip():
            continue
        try:
            json.loads(line)
        except json.JSONDecodeError as e:
            print(f"line {n}: {e}")
            bad += 1
print("ok" if not bad else f"{bad} bad line(s)")
sys.exit(1 if bad else 0)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Top N per group (SQL)

Language: sql

Window-function query: best 3 items in each category.

Run: Run in SQLite 3.25+, PostgreSQL or MySQL 8+.

sql
-- top 3 products by sales in each category
SELECT category, product, sales
FROM (
  SELECT category, product, sales,
         ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn
  FROM product_sales
) ranked
WHERE rn <= 3
ORDER BY category, sales DESC;
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Normalize dates to ISO 8601 with time zone

Language: python

Parses common date formats and prints ISO timestamps in a chosen zone.

Run: python3 iso_dates.py America/Los_Angeles '11/19/2026 23:48'

python
#!/usr/bin/env python3
"""iso_dates.py <tz> <date> [date...]"""
import sys
from datetime import datetime
from zoneinfo import ZoneInfo

FORMATS = ["%Y-%m-%d %H:%M", "%Y-%m-%d", "%m/%d/%Y %H:%M", "%m/%d/%Y", "%d %b %Y"]
tz = ZoneInfo(sys.argv[1])
for raw in sys.argv[2:]:
    for fmt in FORMATS:
        try:
            print(datetime.strptime(raw, fmt).replace(tzinfo=tz).isoformat())
            break
        except ValueError:
            continue
    else:
        print(f"unparsed: {raw}", file=sys.stderr)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Web (5)

Broken link checker for one page

Language: python

Finds links on a page and reports any that fail (stdlib only).

Run: python3 linkcheck.py https://example.com

python
#!/usr/bin/env python3
"""linkcheck.py <page-url> - HEAD each link, falls back to GET."""
import sys
import urllib.request
from html.parser import HTMLParser
from urllib.parse import urljoin

UA = {"User-Agent": "linkcheck-example/1.0"}

class Links(HTMLParser):
    def __init__(self):
        super().__init__()
        self.found = set()
    def handle_starttag(self, tag, attrs):
        href = dict(attrs).get("href")
        if tag == "a" and href and href.startswith(("http", "/")):
            self.found.add(href)

def status(url):
    for method in ("HEAD", "GET"):
        try:
            req = urllib.request.Request(url, method=method, headers=UA)
            with urllib.request.urlopen(req, timeout=10) as r:
                return r.status
        except Exception as e:
            err = getattr(e, "code", str(e))
    return err

page = sys.argv[1]
html = urllib.request.urlopen(urllib.request.Request(page, headers=UA), timeout=10).read().decode("utf-8", "replace")
p = Links()
p.feed(html)
for href in sorted(p.found):
    url = urljoin(page, href)
    s = status(url)
    if s != 200:
        print(s, url)
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

sitemap.xml from a folder of HTML

Language: python

Builds a sitemap for a static site folder.

Run: python3 sitemap.py ./site https://example.com > site/sitemap.xml

python
#!/usr/bin/env python3
"""sitemap.py <site-dir> <base-url>"""
import pathlib
import sys
from datetime import datetime, timezone
from xml.sax.saxutils import escape

root, base = pathlib.Path(sys.argv[1]), sys.argv[2].rstrip("/")
print('<?xml version="1.0" encoding="UTF-8"?>')
print('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
for f in sorted(root.rglob("*.html")):
    rel = f.relative_to(root).as_posix()
    rel = rel[:-10] if rel.endswith("index.html") else rel
    mod = datetime.fromtimestamp(f.stat().st_mtime, timezone.utc).date().isoformat()
    print(f"  <url><loc>{escape(base + '/' + rel)}</loc><lastmod>{mod}</lastmod></url>")
print("</urlset>")
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

robots.txt that welcomes AI crawlers

Language: text

Allows search and AI crawlers and points them to your sitemap and llms.txt.

Run: Save as /robots.txt at your site root.

text
# robots.txt
User-agent: *
Allow: /

User-agent: GPTBot
Allow: /

User-agent: ClaudeBot
Allow: /

User-agent: PerplexityBot
Allow: /

User-agent: Google-Extended
Allow: /

Sitemap: https://example.com/sitemap.xml
# AI-friendly summary: https://example.com/llms.txt
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

JSON-LD ItemList for a list page

Language: html

Structured data so search engines understand your list.

Run: Paste inside <head> and fill in your items.

html
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "ItemList",
  "name": "Best AI tools",
  "itemListElement": [
    {"@type": "ListItem", "position": 1, "name": "Tool A", "url": "https://example.com/a"},
    {"@type": "ListItem", "position": 2, "name": "Tool B", "url": "https://example.com/b"}
  ]
}
</script>
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Check a site's security headers

Language: bash

Shows which common security headers a URL sends.

Run: ./headers.sh https://example.com

bash
#!/usr/bin/env bash
# headers.sh <url>
set -euo pipefail
url="${1:?url}"
hdrs="$(curl -sSI -L "$url" | tr -d '\r')"
for h in strict-transport-security content-security-policy x-content-type-options referrer-policy permissions-policy; do
  if grep -qi "^$h:" <<<"$hdrs"; then echo "OK      $h"; else echo "MISSING $h"; fi
done
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

DevOps (5)

Minimal Python Dockerfile

Language: dockerfile

Small, non-root image for a Python app.

Run: docker build -t myapp . && docker run --rm -p 8000:8000 myapp

dockerfile
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m app
USER app
EXPOSE 8000
CMD ["python", "-m", "http.server", "8000"]
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

GitHub Actions: Python tests on every push

Language: yaml

CI that installs dependencies and runs pytest.

Run: Save as .github/workflows/ci.yml in your repo.

yaml
name: ci
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt pytest
      - run: pytest -q
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Disk space alert

Language: bash

Warns when any mounted filesystem passes a usage threshold.

Run: ./disk-alert.sh 85

bash
#!/usr/bin/env bash
# disk-alert.sh [percent=90] - exit 1 if any filesystem is above the threshold
set -euo pipefail
limit="${1:-90}"; alert=0
while read -r use mount; do
  pct="${use%\%}"
  if [ "$pct" -ge "$limit" ]; then echo "WARN $mount at ${pct}%"; alert=1; fi
done < <(df -P -x tmpfs -x devtmpfs | awk 'NR>1 {print $5, $6}')
exit "$alert"
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Docker cleanup (dry-run first)

Language: bash

Shows what Docker would reclaim, then prunes only with --apply.

Run: ./docker-clean.sh # then ./docker-clean.sh --apply

bash
#!/usr/bin/env bash
# docker-clean.sh [--apply]
set -euo pipefail
docker system df
if [ "${1:-}" = "--apply" ]; then
  docker container prune -f
  docker image prune -f
  docker builder prune -f
  docker system df
else
  echo "dry-run: re-run with --apply to prune stopped containers, dangling images and build cache"
fi
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

TLS certificate expiry check

Language: bash

Prints when a site's certificate expires and days left.

Run: ./cert-days.sh example.com

bash
#!/usr/bin/env bash
# cert-days.sh <host> [port=443]
set -euo pipefail
host="${1:?host}"; port="${2:-443}"
end="$(echo | openssl s_client -servername "$host" -connect "$host:$port" 2>/dev/null \
      | openssl x509 -noout -enddate | cut -d= -f2)"
days=$(( ( $(date -d "$end" +%s) - $(date +%s) ) / 86400 ))
echo "$host expires $end ($days days)"
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Prompts for agents (5)

Minimal tool-calling agent loop

Language: python

A tiny agent loop for any OpenAI-compatible chat API with one safe tool. Stdlib only.

Run: API_BASE=https://api.openai.com/v1 API_KEY=... MODEL=<model> python3 agent_loop.py 'What time is it in Tokyo?'

python
#!/usr/bin/env python3
"""agent_loop.py <question> - env: API_BASE, API_KEY, MODEL. Key is read from env, never printed."""
import json
import os
import sys
import urllib.request
from datetime import datetime
from zoneinfo import ZoneInfo

TOOLS = [{"type": "function", "function": {
    "name": "now_in", "description": "Current time in an IANA time zone",
    "parameters": {"type": "object", "properties": {"tz": {"type": "string"}}, "required": ["tz"]}}}]

def now_in(tz):
    return datetime.now(ZoneInfo(tz)).isoformat(timespec="minutes")

def chat(messages):
    body = json.dumps({"model": os.environ["MODEL"], "messages": messages, "tools": TOOLS}).encode()
    req = urllib.request.Request(os.environ["API_BASE"].rstrip("/") + "/chat/completions", data=body,
                                 headers={"Authorization": "Bearer " + os.environ["API_KEY"],
                                          "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.load(r)["choices"][0]["message"]

messages = [{"role": "user", "content": sys.argv[1]}]
for _ in range(5):  # hard cap on loop turns
    msg = chat(messages)
    messages.append(msg)
    calls = msg.get("tool_calls") or []
    if not calls:
        print(msg.get("content"))
        break
    for c in calls:
        args = json.loads(c["function"]["arguments"])
        result = now_in(**args) if c["function"]["name"] == "now_in" else "unknown tool"
        messages.append({"role": "tool", "tool_call_id": c["id"], "content": result})
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Agent brief template

Language: text

A bounded task brief that keeps agents on track.

Run: Paste into any agent and fill in the brackets.

text
GOAL: <one sentence>
CONTEXT: <files, links, what already exists>
DO:
  1. <step>
  2. <step>
DON'T: delete anything, send messages, spend money, or touch <x> without asking.
DONE WHEN: <a check anyone can run>
REPORT: what changed (paths), what you verified and how, what's left or blocked.
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Structured extraction prompt

Language: text

Gets clean JSON out of messy text, with nulls instead of guesses.

Run: Paste with your text; parse the reply as JSON.

text
Extract the fields below from the text. Rules:
- Output ONLY a JSON object, no prose.
- Use null when the text does not state a value. Never guess.
- Dates as YYYY-MM-DD.
Fields: {"name": string, "company": string, "email": string, "date": string, "amount": number}

TEXT:
<<<
<paste text here>
>>>
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Code-review prompt with severities

Language: text

Consistent, skimmable review output.

Run: Paste with a diff.

text
Review the diff below as a senior engineer.
For each issue output one line: [HIGH|MED|LOW] file:line - problem - suggested fix.
Check: correctness, security (injection, secrets, auth), error handling, tests, naming.
End with: VERDICT: approve | request changes, and one sentence why.

DIFF:
<paste diff>
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

Verify-before-done prompt

Language: text

Makes an agent prove its work before claiming success.

Run: Append to the end of any agent task.

text
Before you report done:
1. Restate the goal in one line.
2. List every requirement and, for each, the evidence it is met (command output, file path, URL + status).
3. List anything you could not verify and why.
4. If any requirement is unmet, say "NOT DONE" first.
βœ“ Checked Nov 20, 2026, 12:03 AM PT New Docs β†—

For AI agents and tools: JSON Β· Markdown Β· llms.txt Β· RSS. Page built Nov 20, 2026, 12:17 AM PT.