@clawhub-xueyetianya-5e1be6a645
Campaign - command-line tool for everyday use Use when you need campaign.
--- name: campaign version: "2.0.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills license: MIT-0 tags: [campaign, tool, utility] description: "Campaign - command-line tool for everyday use Use when you need campaign." --- # Campaign Campaign manager — plan campaigns, track performance, A/B testing, budget allocation, timeline management, and ROI reporting. ## Commands | Command | Description | |---------|-------------| | `campaign run` | Execute main function | | `campaign list` | List all items | | `campaign add <item>` | Add new item | | `campaign status` | Show current status | | `campaign export <format>` | Export data | | `campaign help` | Show help | ## Usage ```bash # Show help campaign help # Quick start campaign run ``` ## Examples ```bash # Run with defaults campaign run # Check status campaign status # Export results campaign export json ``` - Run `campaign help` for all commands - Data stored in `~/.local/share/campaign/` --- *Powered by BytesAgain | bytesagain.com* *Feedback & Feature Requests: https://bytesagain.com/feedback* - Run `campaign help` for all commands ## When to Use - Quick campaign tasks from terminal - Automation pipelines FILE:scripts/script.sh #!/usr/bin/env bash # Campaign — content tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/campaign" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "campaign v2.0.0"; } _help() { echo "Campaign v2.0.0 — content toolkit" echo "" echo "Usage: campaign <command> [args]" echo "" echo "Commands:" echo " draft Draft" echo " edit Edit" echo " optimize Optimize" echo " schedule Schedule" echo " hashtags Hashtags" echo " hooks Hooks" echo " cta Cta" echo " rewrite Rewrite" echo " translate Translate" echo " tone Tone" echo " headline Headline" echo " outline Outline" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Campaign Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Campaign Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Campaign Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: campaign search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in draft) shift if [ $# -eq 0 ]; then echo "Recent draft entries:" tail -20 "$DATA_DIR/draft.log" 2>/dev/null || echo " No entries yet. Use: campaign draft <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/draft.log" local total=$(wc -l < "$DATA_DIR/draft.log") echo " [Campaign] draft: $input" echo " Saved. Total draft entries: $total" _log "draft" "$input" fi ;; edit) shift if [ $# -eq 0 ]; then echo "Recent edit entries:" tail -20 "$DATA_DIR/edit.log" 2>/dev/null || echo " No entries yet. Use: campaign edit <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/edit.log" local total=$(wc -l < "$DATA_DIR/edit.log") echo " [Campaign] edit: $input" echo " Saved. Total edit entries: $total" _log "edit" "$input" fi ;; optimize) shift if [ $# -eq 0 ]; then echo "Recent optimize entries:" tail -20 "$DATA_DIR/optimize.log" 2>/dev/null || echo " No entries yet. Use: campaign optimize <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/optimize.log" local total=$(wc -l < "$DATA_DIR/optimize.log") echo " [Campaign] optimize: $input" echo " Saved. Total optimize entries: $total" _log "optimize" "$input" fi ;; schedule) shift if [ $# -eq 0 ]; then echo "Recent schedule entries:" tail -20 "$DATA_DIR/schedule.log" 2>/dev/null || echo " No entries yet. Use: campaign schedule <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/schedule.log" local total=$(wc -l < "$DATA_DIR/schedule.log") echo " [Campaign] schedule: $input" echo " Saved. Total schedule entries: $total" _log "schedule" "$input" fi ;; hashtags) shift if [ $# -eq 0 ]; then echo "Recent hashtags entries:" tail -20 "$DATA_DIR/hashtags.log" 2>/dev/null || echo " No entries yet. Use: campaign hashtags <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/hashtags.log" local total=$(wc -l < "$DATA_DIR/hashtags.log") echo " [Campaign] hashtags: $input" echo " Saved. Total hashtags entries: $total" _log "hashtags" "$input" fi ;; hooks) shift if [ $# -eq 0 ]; then echo "Recent hooks entries:" tail -20 "$DATA_DIR/hooks.log" 2>/dev/null || echo " No entries yet. Use: campaign hooks <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/hooks.log" local total=$(wc -l < "$DATA_DIR/hooks.log") echo " [Campaign] hooks: $input" echo " Saved. Total hooks entries: $total" _log "hooks" "$input" fi ;; cta) shift if [ $# -eq 0 ]; then echo "Recent cta entries:" tail -20 "$DATA_DIR/cta.log" 2>/dev/null || echo " No entries yet. Use: campaign cta <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/cta.log" local total=$(wc -l < "$DATA_DIR/cta.log") echo " [Campaign] cta: $input" echo " Saved. Total cta entries: $total" _log "cta" "$input" fi ;; rewrite) shift if [ $# -eq 0 ]; then echo "Recent rewrite entries:" tail -20 "$DATA_DIR/rewrite.log" 2>/dev/null || echo " No entries yet. Use: campaign rewrite <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/rewrite.log" local total=$(wc -l < "$DATA_DIR/rewrite.log") echo " [Campaign] rewrite: $input" echo " Saved. Total rewrite entries: $total" _log "rewrite" "$input" fi ;; translate) shift if [ $# -eq 0 ]; then echo "Recent translate entries:" tail -20 "$DATA_DIR/translate.log" 2>/dev/null || echo " No entries yet. Use: campaign translate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/translate.log" local total=$(wc -l < "$DATA_DIR/translate.log") echo " [Campaign] translate: $input" echo " Saved. Total translate entries: $total" _log "translate" "$input" fi ;; tone) shift if [ $# -eq 0 ]; then echo "Recent tone entries:" tail -20 "$DATA_DIR/tone.log" 2>/dev/null || echo " No entries yet. Use: campaign tone <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/tone.log" local total=$(wc -l < "$DATA_DIR/tone.log") echo " [Campaign] tone: $input" echo " Saved. Total tone entries: $total" _log "tone" "$input" fi ;; headline) shift if [ $# -eq 0 ]; then echo "Recent headline entries:" tail -20 "$DATA_DIR/headline.log" 2>/dev/null || echo " No entries yet. Use: campaign headline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/headline.log" local total=$(wc -l < "$DATA_DIR/headline.log") echo " [Campaign] headline: $input" echo " Saved. Total headline entries: $total" _log "headline" "$input" fi ;; outline) shift if [ $# -eq 0 ]; then echo "Recent outline entries:" tail -20 "$DATA_DIR/outline.log" 2>/dev/null || echo " No entries yet. Use: campaign outline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/outline.log" local total=$(wc -l < "$DATA_DIR/outline.log") echo " [Campaign] outline: $input" echo " Saved. Total outline entries: $total" _log "outline" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'campaign help' for available commands." exit 1 ;; esac
Track trending topics with popularity, sentiment, and alerts. Use when drafting reports, optimizing keywords, scheduling checks, tagging hashtags.
--- name: trend version: "2.0.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills license: MIT-0 tags: [trend, tool, utility] description: "Track trending topics with popularity, sentiment, and alerts. Use when drafting reports, optimizing keywords, scheduling checks, tagging hashtags." --- # Trend Content creation and management toolkit. Draft posts, edit content, optimize for engagement, schedule publications, generate hashtags, write hooks and CTAs, rewrite text, translate content, adjust tone, craft headlines, and build outlines. All entries are timestamped and stored locally for full traceability. ## Commands ### Content Creation | Command | Description | |---------|-------------| | `trend draft [input]` | Draft new content (no args = show recent drafts) | | `trend edit [input]` | Edit/refine content (no args = show recent edits) | | `trend rewrite [input]` | Rewrite existing content (no args = show recent rewrites) | | `trend headline [input]` | Craft headlines (no args = show recent headlines) | | `trend outline [input]` | Build content outlines (no args = show recent outlines) | ### Content Optimization | Command | Description | |---------|-------------| | `trend optimize [input]` | Optimize content for engagement (no args = show recent) | | `trend hashtags [input]` | Generate hashtags (no args = show recent) | | `trend hooks [input]` | Write attention-grabbing hooks (no args = show recent) | | `trend cta [input]` | Create calls-to-action (no args = show recent) | | `trend tone [input]` | Adjust content tone (no args = show recent) | ### Publishing | Command | Description | |---------|-------------| | `trend schedule [input]` | Schedule content for publication (no args = show recent) | | `trend translate [input]` | Translate content (no args = show recent translations) | ### Data & Reporting | Command | Description | |---------|-------------| | `trend stats` | Summary statistics across all entry types | | `trend export <fmt>` | Export all data (json, csv, or txt) | | `trend search <term>` | Search across all entries | | `trend recent` | Show last 20 activity log entries | | `trend status` | Health check: version, entry count, disk usage, last activity | ### Utility | Command | Description | |---------|-------------| | `trend help` | Show help with all commands | | `trend version` | Show version number | ## Data Storage All data is stored locally at `~/.local/share/trend/` by default: - `draft.log`, `edit.log`, `optimize.log`, etc. — One log file per command type, entries are `timestamp|input` format - `history.log` — Unified activity history with timestamps for every command run - `export.json`, `export.csv`, `export.txt` — Generated export files Each command supports two modes: - **With arguments:** Saves the input with a timestamp and confirms - **Without arguments:** Shows the 20 most recent entries for that command type ## Requirements - bash 4+ - Standard UNIX utilities (`date`, `wc`, `du`, `grep`, `tail`, `head`, `sed`, `cut`) - No external dependencies or API keys required ## When to Use 1. **Content drafting workflow** — Use `draft` to capture ideas, `outline` to structure them, `headline` to title them, then `edit` to refine 2. **Social media optimization** — Run `hashtags` for tags, `hooks` for attention-grabbing openers, `cta` for calls-to-action, and `tone` to match platform voice 3. **Content scheduling** — Use `schedule` to log publication timelines and `translate` to prepare multi-language versions 4. **Content audit** — Run `stats` to see activity across all content types, `search` to find specific entries, and `recent` to review the latest work 5. **Data export and backup** — Use `export json` for structured data, `export csv` for spreadsheet import, or `export txt` for readable dumps ## Examples ```bash # Draft a new blog post idea trend draft "10 tips for better remote work productivity" # View all recent drafts trend draft # Create an outline for the post trend outline "Intro, 10 tips with examples, conclusion with CTA" # Craft a headline trend headline "Remote Work Productivity: 10 Tips That Actually Work" # Generate hashtags for social media trend hashtags "#remotework #productivity #wfh #tipsandtricks" # Write a hook for the post trend hooks "Most remote workers waste 3 hours a day. Here's how to fix that." # Create a call-to-action trend cta "Download our free remote work checklist" # Optimize the content trend optimize "Added power words, shortened paragraphs, added bullet points" # Adjust tone for LinkedIn trend tone "Professional but approachable, data-driven" # Schedule for publication trend schedule "Publish Monday 9am EST on blog, noon on LinkedIn" # Translate to another language trend translate "Spanish version for LATAM audience" # Rewrite an existing section trend rewrite "Simplified the introduction, removed jargon" # Edit the final draft trend edit "Final proofread, fixed typos, added links" # Check overall stats trend stats # Export all data as JSON trend export json # Search for a specific topic trend search "productivity" # View recent activity trend recent # Health check trend status ``` ## Tips - Every command with input is automatically timestamped and logged — nothing is lost - Run commands without arguments to review your recent entries (shows last 20) - Use `stats` to see entry counts per command type for a bird's-eye view - Export supports three formats: `json` (structured), `csv` (spreadsheets), `txt` (human-readable) - All log files are plain text and can be edited or grepped directly --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash # Trend — content tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/trend" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "trend v2.0.0"; } _help() { echo "Trend v2.0.0 — content toolkit" echo "" echo "Usage: trend <command> [args]" echo "" echo "Commands:" echo " draft Draft" echo " edit Edit" echo " optimize Optimize" echo " schedule Schedule" echo " hashtags Hashtags" echo " hooks Hooks" echo " cta Cta" echo " rewrite Rewrite" echo " translate Translate" echo " tone Tone" echo " headline Headline" echo " outline Outline" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Trend Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Trend Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Trend Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: trend search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in draft) shift if [ $# -eq 0 ]; then echo "Recent draft entries:" tail -20 "$DATA_DIR/draft.log" 2>/dev/null || echo " No entries yet. Use: trend draft <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/draft.log" local total=$(wc -l < "$DATA_DIR/draft.log") echo " [Trend] draft: $input" echo " Saved. Total draft entries: $total" _log "draft" "$input" fi ;; edit) shift if [ $# -eq 0 ]; then echo "Recent edit entries:" tail -20 "$DATA_DIR/edit.log" 2>/dev/null || echo " No entries yet. Use: trend edit <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/edit.log" local total=$(wc -l < "$DATA_DIR/edit.log") echo " [Trend] edit: $input" echo " Saved. Total edit entries: $total" _log "edit" "$input" fi ;; optimize) shift if [ $# -eq 0 ]; then echo "Recent optimize entries:" tail -20 "$DATA_DIR/optimize.log" 2>/dev/null || echo " No entries yet. Use: trend optimize <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/optimize.log" local total=$(wc -l < "$DATA_DIR/optimize.log") echo " [Trend] optimize: $input" echo " Saved. Total optimize entries: $total" _log "optimize" "$input" fi ;; schedule) shift if [ $# -eq 0 ]; then echo "Recent schedule entries:" tail -20 "$DATA_DIR/schedule.log" 2>/dev/null || echo " No entries yet. Use: trend schedule <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/schedule.log" local total=$(wc -l < "$DATA_DIR/schedule.log") echo " [Trend] schedule: $input" echo " Saved. Total schedule entries: $total" _log "schedule" "$input" fi ;; hashtags) shift if [ $# -eq 0 ]; then echo "Recent hashtags entries:" tail -20 "$DATA_DIR/hashtags.log" 2>/dev/null || echo " No entries yet. Use: trend hashtags <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/hashtags.log" local total=$(wc -l < "$DATA_DIR/hashtags.log") echo " [Trend] hashtags: $input" echo " Saved. Total hashtags entries: $total" _log "hashtags" "$input" fi ;; hooks) shift if [ $# -eq 0 ]; then echo "Recent hooks entries:" tail -20 "$DATA_DIR/hooks.log" 2>/dev/null || echo " No entries yet. Use: trend hooks <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/hooks.log" local total=$(wc -l < "$DATA_DIR/hooks.log") echo " [Trend] hooks: $input" echo " Saved. Total hooks entries: $total" _log "hooks" "$input" fi ;; cta) shift if [ $# -eq 0 ]; then echo "Recent cta entries:" tail -20 "$DATA_DIR/cta.log" 2>/dev/null || echo " No entries yet. Use: trend cta <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/cta.log" local total=$(wc -l < "$DATA_DIR/cta.log") echo " [Trend] cta: $input" echo " Saved. Total cta entries: $total" _log "cta" "$input" fi ;; rewrite) shift if [ $# -eq 0 ]; then echo "Recent rewrite entries:" tail -20 "$DATA_DIR/rewrite.log" 2>/dev/null || echo " No entries yet. Use: trend rewrite <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/rewrite.log" local total=$(wc -l < "$DATA_DIR/rewrite.log") echo " [Trend] rewrite: $input" echo " Saved. Total rewrite entries: $total" _log "rewrite" "$input" fi ;; translate) shift if [ $# -eq 0 ]; then echo "Recent translate entries:" tail -20 "$DATA_DIR/translate.log" 2>/dev/null || echo " No entries yet. Use: trend translate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/translate.log" local total=$(wc -l < "$DATA_DIR/translate.log") echo " [Trend] translate: $input" echo " Saved. Total translate entries: $total" _log "translate" "$input" fi ;; tone) shift if [ $# -eq 0 ]; then echo "Recent tone entries:" tail -20 "$DATA_DIR/tone.log" 2>/dev/null || echo " No entries yet. Use: trend tone <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/tone.log" local total=$(wc -l < "$DATA_DIR/tone.log") echo " [Trend] tone: $input" echo " Saved. Total tone entries: $total" _log "tone" "$input" fi ;; headline) shift if [ $# -eq 0 ]; then echo "Recent headline entries:" tail -20 "$DATA_DIR/headline.log" 2>/dev/null || echo " No entries yet. Use: trend headline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/headline.log" local total=$(wc -l < "$DATA_DIR/headline.log") echo " [Trend] headline: $input" echo " Saved. Total headline entries: $total" _log "headline" "$input" fi ;; outline) shift if [ $# -eq 0 ]; then echo "Recent outline entries:" tail -20 "$DATA_DIR/outline.log" 2>/dev/null || echo " No entries yet. Use: trend outline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/outline.log" local total=$(wc -l < "$DATA_DIR/outline.log") echo " [Trend] outline: $input" echo " Saved. Total outline entries: $total" _log "outline" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'trend help' for available commands." exit 1 ;; esac
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Hashtag concepts, best practices, and implementation patterns.
--- name: "hashtag" version: "2.0.4" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Hashtag concepts, best practices, and implementation patterns." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [hashtag, reference] category: "devtools" --- # Hashtag Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Hashtag concepts, best practices, and implementation patterns. No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # hashtag — Hashtag reference tool. Use when working with hashtag in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.3" show_help() { cat << 'HELPEOF' hashtag v$VERSION — Hashtag Reference Tool Usage: hashtag <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Hashtag — Overview ## What is Hashtag? Hashtag (hashtag) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with hashtag. ## Key Concepts - Core hashtag principles and fundamentals - How hashtag fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Hashtag Matters Understanding hashtag is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic hashtag concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Hashtag — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the hashtag package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Hashtag — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for hashtag 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Hashtag — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Hashtag — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Hashtag — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Hashtag — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Hashtag — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "hashtag v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: hashtag help"; exit 1 ;; esac
Changelog - command-line tool for everyday use Use when you need changelog.
--- name: changelog version: "2.0.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills license: MIT-0 tags: [changelog, tool, utility] description: "Changelog - command-line tool for everyday use Use when you need changelog." --- # Changelog Changelog generator — commit parsing, version grouping, markdown output, conventional commits, breaking change detection, and templates. ## Commands | Command | Description | |---------|-------------| | `changelog run` | Execute main function | | `changelog list` | List all items | | `changelog add <item>` | Add new item | | `changelog status` | Show current status | | `changelog export <format>` | Export data | | `changelog help` | Show help | ## Usage ```bash # Show help changelog help # Quick start changelog run ``` ## Examples ```bash # Run with defaults changelog run # Check status changelog status # Export results changelog export json ``` - Run `changelog help` for all commands - Data stored in `~/.local/share/changelog/` --- *Powered by BytesAgain | bytesagain.com* *Feedback & Feature Requests: https://bytesagain.com/feedback* - Run `changelog help` for all commands ## When to Use - Quick changelog tasks from terminal - Automation pipelines FILE:scripts/script.sh #!/usr/bin/env bash # Changelog — devtools tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/changelog" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "changelog v2.0.0"; } _help() { echo "Changelog v2.0.0 — devtools toolkit" echo "" echo "Usage: changelog <command> [args]" echo "" echo "Commands:" echo " check Check" echo " validate Validate" echo " generate Generate" echo " format Format" echo " lint Lint" echo " explain Explain" echo " convert Convert" echo " template Template" echo " diff Diff" echo " preview Preview" echo " fix Fix" echo " report Report" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Changelog Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Changelog Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Changelog Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: changelog search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in check) shift if [ $# -eq 0 ]; then echo "Recent check entries:" tail -20 "$DATA_DIR/check.log" 2>/dev/null || echo " No entries yet. Use: changelog check <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/check.log" local total=$(wc -l < "$DATA_DIR/check.log") echo " [Changelog] check: $input" echo " Saved. Total check entries: $total" _log "check" "$input" fi ;; validate) shift if [ $# -eq 0 ]; then echo "Recent validate entries:" tail -20 "$DATA_DIR/validate.log" 2>/dev/null || echo " No entries yet. Use: changelog validate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/validate.log" local total=$(wc -l < "$DATA_DIR/validate.log") echo " [Changelog] validate: $input" echo " Saved. Total validate entries: $total" _log "validate" "$input" fi ;; generate) shift if [ $# -eq 0 ]; then echo "Recent generate entries:" tail -20 "$DATA_DIR/generate.log" 2>/dev/null || echo " No entries yet. Use: changelog generate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/generate.log" local total=$(wc -l < "$DATA_DIR/generate.log") echo " [Changelog] generate: $input" echo " Saved. Total generate entries: $total" _log "generate" "$input" fi ;; format) shift if [ $# -eq 0 ]; then echo "Recent format entries:" tail -20 "$DATA_DIR/format.log" 2>/dev/null || echo " No entries yet. Use: changelog format <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/format.log" local total=$(wc -l < "$DATA_DIR/format.log") echo " [Changelog] format: $input" echo " Saved. Total format entries: $total" _log "format" "$input" fi ;; lint) shift if [ $# -eq 0 ]; then echo "Recent lint entries:" tail -20 "$DATA_DIR/lint.log" 2>/dev/null || echo " No entries yet. Use: changelog lint <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/lint.log" local total=$(wc -l < "$DATA_DIR/lint.log") echo " [Changelog] lint: $input" echo " Saved. Total lint entries: $total" _log "lint" "$input" fi ;; explain) shift if [ $# -eq 0 ]; then echo "Recent explain entries:" tail -20 "$DATA_DIR/explain.log" 2>/dev/null || echo " No entries yet. Use: changelog explain <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/explain.log" local total=$(wc -l < "$DATA_DIR/explain.log") echo " [Changelog] explain: $input" echo " Saved. Total explain entries: $total" _log "explain" "$input" fi ;; convert) shift if [ $# -eq 0 ]; then echo "Recent convert entries:" tail -20 "$DATA_DIR/convert.log" 2>/dev/null || echo " No entries yet. Use: changelog convert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/convert.log" local total=$(wc -l < "$DATA_DIR/convert.log") echo " [Changelog] convert: $input" echo " Saved. Total convert entries: $total" _log "convert" "$input" fi ;; template) shift if [ $# -eq 0 ]; then echo "Recent template entries:" tail -20 "$DATA_DIR/template.log" 2>/dev/null || echo " No entries yet. Use: changelog template <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/template.log" local total=$(wc -l < "$DATA_DIR/template.log") echo " [Changelog] template: $input" echo " Saved. Total template entries: $total" _log "template" "$input" fi ;; diff) shift if [ $# -eq 0 ]; then echo "Recent diff entries:" tail -20 "$DATA_DIR/diff.log" 2>/dev/null || echo " No entries yet. Use: changelog diff <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/diff.log" local total=$(wc -l < "$DATA_DIR/diff.log") echo " [Changelog] diff: $input" echo " Saved. Total diff entries: $total" _log "diff" "$input" fi ;; preview) shift if [ $# -eq 0 ]; then echo "Recent preview entries:" tail -20 "$DATA_DIR/preview.log" 2>/dev/null || echo " No entries yet. Use: changelog preview <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/preview.log" local total=$(wc -l < "$DATA_DIR/preview.log") echo " [Changelog] preview: $input" echo " Saved. Total preview entries: $total" _log "preview" "$input" fi ;; fix) shift if [ $# -eq 0 ]; then echo "Recent fix entries:" tail -20 "$DATA_DIR/fix.log" 2>/dev/null || echo " No entries yet. Use: changelog fix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/fix.log" local total=$(wc -l < "$DATA_DIR/fix.log") echo " [Changelog] fix: $input" echo " Saved. Total fix entries: $total" _log "fix" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: changelog report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Changelog] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'changelog help' for available commands." exit 1 ;; esac
Check code syntax, enforce style, and suggest auto-fixes with CI integration. Use when linting PRs, enforcing code style, detecting errors before merge.
--- name: lint version: "2.0.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills license: MIT-0 tags: [lint, tool, utility] description: "Check code syntax, enforce style, and suggest auto-fixes with CI integration. Use when linting PRs, enforcing code style, detecting errors before merge." --- # Lint Lint is a developer-focused toolkit for recording and tracking code quality operations from the terminal. It provides 13 core action commands for managing checks, validations, formatting, linting, code generation, conversions, templates, diffs, previews, fixes, reports, and explanations — all with timestamped local logging for full traceability. Additional utility commands let you view statistics, export data, search history, and monitor health status. ## Commands ### Core Action Commands Each action command works in two modes: run without arguments to view the 20 most recent entries, or pass input text to record a new timestamped entry. | Command | Description | |---------|-------------| | `lint check <input>` | Record a syntax/code check entry | | `lint validate <input>` | Record a validation result | | `lint generate <input>` | Record a code generation action | | `lint format <input>` | Record a formatting operation | | `lint lint <input>` | Record a linting pass | | `lint explain <input>` | Record an explanation or annotation | | `lint convert <input>` | Record a conversion operation | | `lint template <input>` | Record a template action | | `lint diff <input>` | Record a diff comparison | | `lint preview <input>` | Record a preview action | | `lint fix <input>` | Record an auto-fix action | | `lint report <input>` | Record a report generation | ### Utility Commands | Command | Description | |---------|-------------| | `lint stats` | Show summary statistics — entry counts per category, total entries, data size, and earliest activity timestamp | | `lint export <fmt>` | Export all data to JSON, CSV, or TXT format. Output file saved to `~/.local/share/lint/export.<fmt>` | | `lint search <term>` | Full-text search across all log files (case-insensitive) | | `lint recent` | Show the 20 most recent entries from the history log | | `lint status` | Health check — version, data directory, total entries, disk usage, last activity | | `lint help` | Show help with all available commands | | `lint version` | Print version string (`lint v2.0.0`) | ## Data Storage All data is stored locally in `~/.local/share/lint/`. Each action command writes to its own log file (e.g., `check.log`, `validate.log`, `fix.log`). A unified `history.log` records every action with timestamps. No external services, databases, or network connections are used. **Directory structure:** ``` ~/.local/share/lint/ ├── check.log # Check entries ├── validate.log # Validation entries ├── generate.log # Generation entries ├── format.log # Formatting entries ├── lint.log # Lint pass entries ├── explain.log # Explanation entries ├── convert.log # Conversion entries ├── template.log # Template entries ├── diff.log # Diff entries ├── preview.log # Preview entries ├── fix.log # Fix entries ├── report.log # Report entries ├── history.log # Unified activity log └── export.* # Export output files ``` ## Requirements - Bash (with `set -euo pipefail`) - Standard Unix utilities: `date`, `wc`, `du`, `head`, `tail`, `grep`, `basename`, `cut` - No external dependencies or API keys required ## When to Use 1. **Tracking linting sessions** — Record which files you linted, what issues you found, and what fixes you applied, all with timestamps for audit trails. 2. **Code review workflows** — Log check and validate results during PR reviews so you can refer back to what was inspected and when. 3. **Template and diff management** — Keep a running record of template operations and diff comparisons across project iterations. 4. **Exporting quality reports** — Use `lint export json` to generate machine-readable reports of all recorded lint activity for CI dashboards or team reviews. 5. **Searching past actions** — Quickly find previous lint results, fixes, or explanations with `lint search <term>` across all categories. ## Examples ```bash # Record a check on a Python file lint check "src/main.py — 3 unused imports found" # Record a fix applied lint fix "Removed unused imports in src/main.py" # View recent formatting actions lint format # Search for all entries mentioning "import" lint search import # Export everything to JSON lint export json # View overall statistics lint stats # Health check lint status ``` --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash # Lint — devtools tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/lint" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "lint v2.0.0"; } _help() { echo "Lint v2.0.0 — devtools toolkit" echo "" echo "Usage: lint <command> [args]" echo "" echo "Commands:" echo " check Check" echo " validate Validate" echo " generate Generate" echo " format Format" echo " lint Lint" echo " explain Explain" echo " convert Convert" echo " template Template" echo " diff Diff" echo " preview Preview" echo " fix Fix" echo " report Report" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Lint Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Lint Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Lint Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: lint search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in check) shift if [ $# -eq 0 ]; then echo "Recent check entries:" tail -20 "$DATA_DIR/check.log" 2>/dev/null || echo " No entries yet. Use: lint check <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/check.log" local total=$(wc -l < "$DATA_DIR/check.log") echo " [Lint] check: $input" echo " Saved. Total check entries: $total" _log "check" "$input" fi ;; validate) shift if [ $# -eq 0 ]; then echo "Recent validate entries:" tail -20 "$DATA_DIR/validate.log" 2>/dev/null || echo " No entries yet. Use: lint validate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/validate.log" local total=$(wc -l < "$DATA_DIR/validate.log") echo " [Lint] validate: $input" echo " Saved. Total validate entries: $total" _log "validate" "$input" fi ;; generate) shift if [ $# -eq 0 ]; then echo "Recent generate entries:" tail -20 "$DATA_DIR/generate.log" 2>/dev/null || echo " No entries yet. Use: lint generate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/generate.log" local total=$(wc -l < "$DATA_DIR/generate.log") echo " [Lint] generate: $input" echo " Saved. Total generate entries: $total" _log "generate" "$input" fi ;; format) shift if [ $# -eq 0 ]; then echo "Recent format entries:" tail -20 "$DATA_DIR/format.log" 2>/dev/null || echo " No entries yet. Use: lint format <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/format.log" local total=$(wc -l < "$DATA_DIR/format.log") echo " [Lint] format: $input" echo " Saved. Total format entries: $total" _log "format" "$input" fi ;; lint) shift if [ $# -eq 0 ]; then echo "Recent lint entries:" tail -20 "$DATA_DIR/lint.log" 2>/dev/null || echo " No entries yet. Use: lint lint <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/lint.log" local total=$(wc -l < "$DATA_DIR/lint.log") echo " [Lint] lint: $input" echo " Saved. Total lint entries: $total" _log "lint" "$input" fi ;; explain) shift if [ $# -eq 0 ]; then echo "Recent explain entries:" tail -20 "$DATA_DIR/explain.log" 2>/dev/null || echo " No entries yet. Use: lint explain <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/explain.log" local total=$(wc -l < "$DATA_DIR/explain.log") echo " [Lint] explain: $input" echo " Saved. Total explain entries: $total" _log "explain" "$input" fi ;; convert) shift if [ $# -eq 0 ]; then echo "Recent convert entries:" tail -20 "$DATA_DIR/convert.log" 2>/dev/null || echo " No entries yet. Use: lint convert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/convert.log" local total=$(wc -l < "$DATA_DIR/convert.log") echo " [Lint] convert: $input" echo " Saved. Total convert entries: $total" _log "convert" "$input" fi ;; template) shift if [ $# -eq 0 ]; then echo "Recent template entries:" tail -20 "$DATA_DIR/template.log" 2>/dev/null || echo " No entries yet. Use: lint template <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/template.log" local total=$(wc -l < "$DATA_DIR/template.log") echo " [Lint] template: $input" echo " Saved. Total template entries: $total" _log "template" "$input" fi ;; diff) shift if [ $# -eq 0 ]; then echo "Recent diff entries:" tail -20 "$DATA_DIR/diff.log" 2>/dev/null || echo " No entries yet. Use: lint diff <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/diff.log" local total=$(wc -l < "$DATA_DIR/diff.log") echo " [Lint] diff: $input" echo " Saved. Total diff entries: $total" _log "diff" "$input" fi ;; preview) shift if [ $# -eq 0 ]; then echo "Recent preview entries:" tail -20 "$DATA_DIR/preview.log" 2>/dev/null || echo " No entries yet. Use: lint preview <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/preview.log" local total=$(wc -l < "$DATA_DIR/preview.log") echo " [Lint] preview: $input" echo " Saved. Total preview entries: $total" _log "preview" "$input" fi ;; fix) shift if [ $# -eq 0 ]; then echo "Recent fix entries:" tail -20 "$DATA_DIR/fix.log" 2>/dev/null || echo " No entries yet. Use: lint fix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/fix.log" local total=$(wc -l < "$DATA_DIR/fix.log") echo " [Lint] fix: $input" echo " Saved. Total fix entries: $total" _log "fix" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: lint report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Lint] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'lint help' for available commands." exit 1 ;; esac
Resize, crop, convert, and optimize images using ImageMagick. Use when processing photos, converting formats (PNG/WebP), compressing size, or adding watermarks.
--- name: "Vision — Image Processing, Resize, Convert & Watermark" description: "Resize, crop, convert, and optimize images using ImageMagick. Use when processing photos, converting formats (PNG/WebP), compressing size, or adding watermarks." version: "3.5.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["vision", "image-processing", "resize", "crop", "convert", "optimize", "exif", "watermark", "图像处理"] --- # vision Image processing toolkit powered by ImageMagick. ## Quick Start / 快速开始 Just ask your AI assistant: / 直接告诉 AI 助手: - "Resize photo.jpg to 800px width" (帮我把 photo.jpg 缩小到 800 宽) - "Convert this PNG to WebP format" (把这张 PNG 图片转换成 WebP 格式) - "Add watermark: © 2025 BytesAgain" (给这张图加个水印) ## Commands ### resize Resize an image. ```bash bash scripts/script.sh resize --input photo.jpg --width 800 bash scripts/script.sh resize --input photo.jpg --percent 50 ``` ### convert Change image formats. ```bash bash scripts/script.sh convert --input photo.png --to webp bash scripts/script.sh convert --input photo.jpg --to png ``` ### optimize Compress file size without losing quality. ```bash bash scripts/script.sh optimize --input photo.jpg --quality 80 ``` ### watermark Add text watermark to images. ```bash bash scripts/script.sh watermark --input photo.jpg --text "© 2025" --position southeast ``` ## Requirements - bash 4+ - ImageMagick (convert, identify) ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ############################################################################### # vision - Image Processing Toolkit # Version: 3.0.0 # Author: BytesAgain # # Commands: resize, crop, convert, optimize, info, watermark # Requires: ImageMagick (convert/identify/mogrify commands) ############################################################################### SCRIPT_DIR="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)" JSON_OUTPUT=false # --------------------------------------------------------------------------- # Utilities # --------------------------------------------------------------------------- die() { echo "ERROR: $*" >&2; exit 1; } log() { echo "[vision] $*" >&2; } check_imagemagick() { if ! command -v convert &>/dev/null && ! command -v magick &>/dev/null; then die "ImageMagick is required but not installed. Install with: apt install imagemagick / brew install imagemagick" fi } # Wrapper to handle both ImageMagick 6 (convert) and 7 (magick) im_convert() { if command -v magick &>/dev/null; then magick "$@" else convert "$@" fi } im_identify() { if command -v magick &>/dev/null; then magick identify "$@" else identify "$@" fi } parse_global_flags() { local args=() for arg in "$@"; do if [[ "$arg" == "--json" ]]; then JSON_OUTPUT=true else args+=("$arg") fi done REMAINING_ARGS=("args[@]+"${args[@]"}") } get_extension() { local filename="$1" echo "filename##*." | tr '[:upper:]' '[:lower:]' } get_basename() { local filename="$1" local base base=$(basename "$filename") echo "base%.*" } get_dirname() { dirname "$1" } auto_output_name() { local input="$1" local suffix="$2" local ext="-$(get_extension "$input")" local dir dir=$(get_dirname "$input") local base base=$(get_basename "$input") echo "dir/base_suffix.ext" } validate_input() { local input="$1" [[ -n "$input" ]] || die "No input file specified. Use --input" [[ -f "$input" ]] || die "File not found: $input" } # --------------------------------------------------------------------------- # cmd_help - List all commands # --------------------------------------------------------------------------- cmd_help() { cat <<'EOF' vision - Image Processing Toolkit Usage: bash script.sh <command> [options] Commands: resize Resize image to dimensions or percentage crop Crop image to a region convert Convert between png, jpg, webp formats optimize Compress image to reduce file size info Read EXIF and image metadata watermark Add text watermark to image help Show this help message Common options: --input Input image file (required for all commands) --output Output file path (auto-generated if omitted) --json JSON output for info command Requires: ImageMagick (apt install imagemagick) Examples: bash script.sh resize --input photo.jpg --width 800 bash script.sh convert --input photo.png --to webp bash script.sh info --input photo.jpg --json EOF } # --------------------------------------------------------------------------- # cmd_resize - Resize image # --------------------------------------------------------------------------- cmd_resize() { check_imagemagick local input="" output="" width="" height="" percent="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --width) shift; width="$1" ;; --height) shift; height="$1" ;; --percent) shift; percent="$1" ;; *) die "Unknown option for resize: $1" ;; esac shift done validate_input "$input" [[ -n "$output" ]] || output=$(auto_output_name "$input" "resized") local geometry="" if [[ -n "$percent" ]]; then geometry="percent%" elif [[ -n "$width" && -n "$height" ]]; then geometry="widthxheight!" elif [[ -n "$width" ]]; then geometry="widthx" elif [[ -n "$height" ]]; then geometry="xheight" else die "resize requires --width, --height, or --percent" fi im_convert "$input" -resize "$geometry" "$output" # Report results local orig_size new_size orig_size=$(stat -c%s "$input" 2>/dev/null || stat -f%z "$input") new_size=$(stat -c%s "$output" 2>/dev/null || stat -f%z "$output") local orig_dims new_dims orig_dims=$(im_identify -format "%wx%h" "$input") new_dims=$(im_identify -format "%wx%h" "$output") echo "Resized: $input → $output" echo " Original: orig_dims ($(( orig_size / 1024 )) KB)" echo " Resized: new_dims ($(( new_size / 1024 )) KB)" } # --------------------------------------------------------------------------- # cmd_crop - Crop image # --------------------------------------------------------------------------- cmd_crop() { check_imagemagick local input="" output="" width="" height="" x="0" y="0" gravity="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --width) shift; width="$1" ;; --height) shift; height="$1" ;; --x) shift; x="$1" ;; --y) shift; y="$1" ;; --gravity) shift; gravity="$1" ;; *) die "Unknown option for crop: $1" ;; esac shift done validate_input "$input" [[ -n "$width" ]] || die "crop requires --width" [[ -n "$height" ]] || die "crop requires --height" [[ -n "$output" ]] || output=$(auto_output_name "$input" "cropped") if [[ -n "$gravity" ]]; then im_convert "$input" -gravity "$gravity" -crop "widthxheight+0+0" +repage "$output" else im_convert "$input" -crop "widthxheight+x+y" +repage "$output" fi local new_dims new_dims=$(im_identify -format "%wx%h" "$output") echo "Cropped: $input → $output" echo " Region: widthxheight+x+y" echo " Result: new_dims" } # --------------------------------------------------------------------------- # cmd_convert - Format conversion # --------------------------------------------------------------------------- cmd_convert() { check_imagemagick local input="" output="" to="" quality="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --to) shift; to="$1" ;; --quality) shift; quality="$1" ;; *) die "Unknown option for convert: $1" ;; esac shift done validate_input "$input" [[ -n "$to" ]] || die "convert requires --to (png, jpg, webp)" # Normalize format name case "$to" in jpeg) to="jpg" ;; esac [[ "$to" =~ ^(png|jpg|webp)$ ]] || die "Supported formats: png, jpg, webp" if [[ -z "$output" ]]; then local dir base dir=$(get_dirname "$input") base=$(get_basename "$input") output="dir/base.to" fi local cmd_args=("$input") [[ -n "$quality" ]] && cmd_args+=(-quality "$quality") cmd_args+=("$output") im_convert "cmd_args[@]" local orig_size new_size orig_size=$(stat -c%s "$input" 2>/dev/null || stat -f%z "$input") new_size=$(stat -c%s "$output" 2>/dev/null || stat -f%z "$output") local orig_ext orig_ext=$(get_extension "$input") echo "Converted: $input ($orig_ext) → $output ($to)" echo " Original: $(( orig_size / 1024 )) KB" echo " Output: $(( new_size / 1024 )) KB" local ratio ratio=$(awk "BEGIN {printf \"%.1f\", $new_size * 100 / $orig_size}") echo " Size: ratio% of original" } # --------------------------------------------------------------------------- # cmd_optimize - Compress image # --------------------------------------------------------------------------- cmd_optimize() { check_imagemagick local input="" output="" quality="85" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --quality) shift; quality="$1" ;; *) die "Unknown option for optimize: $1" ;; esac shift done validate_input "$input" [[ -n "$output" ]] || output=$(auto_output_name "$input" "optimized") local ext ext=$(get_extension "$input") local orig_size orig_size=$(stat -c%s "$input" 2>/dev/null || stat -f%z "$input") case "$ext" in jpg|jpeg) im_convert "$input" -quality "$quality" -sampling-factor 4:2:0 -strip \ -interlace JPEG "$output" ;; png) im_convert "$input" -quality "$quality" -strip -define png:compression-level=9 "$output" ;; webp) im_convert "$input" -quality "$quality" -define webp:method=6 "$output" ;; *) im_convert "$input" -quality "$quality" -strip "$output" ;; esac local new_size new_size=$(stat -c%s "$output" 2>/dev/null || stat -f%z "$output") local saved=$((orig_size - new_size)) local ratio ratio=$(awk "BEGIN {printf \"%.1f\", $new_size * 100 / $orig_size}") echo "Optimized: $input → $output" echo " Original: $(( orig_size / 1024 )) KB" echo " Output: $(( new_size / 1024 )) KB" echo " Saved: $(( saved / 1024 )) KB (ratio% of original)" echo " Quality: $quality" } # --------------------------------------------------------------------------- # cmd_info - Read EXIF and metadata # --------------------------------------------------------------------------- cmd_info() { check_imagemagick local input="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; *) die "Unknown option for info: $1" ;; esac shift done validate_input "$input" local format width height colorspace depth filesize format=$(im_identify -format "%m" "$input" 2>/dev/null | head -1) width=$(im_identify -format "%w" "$input" 2>/dev/null | head -1) height=$(im_identify -format "%h" "$input" 2>/dev/null | head -1) colorspace=$(im_identify -format "%[colorspace]" "$input" 2>/dev/null | head -1) depth=$(im_identify -format "%z" "$input" 2>/dev/null | head -1) filesize=$(stat -c%s "$input" 2>/dev/null || stat -f%z "$input") # Try to get EXIF data local exif_make="" exif_model="" exif_date="" exif_exposure="" exif_iso="" exif_focal="" if command -v exiftool &>/dev/null; then exif_make=$(exiftool -Make -s3 "$input" 2>/dev/null || true) exif_model=$(exiftool -Model -s3 "$input" 2>/dev/null || true) exif_date=$(exiftool -DateTimeOriginal -s3 "$input" 2>/dev/null || true) exif_exposure=$(exiftool -ExposureTime -s3 "$input" 2>/dev/null || true) exif_iso=$(exiftool -ISO -s3 "$input" 2>/dev/null || true) exif_focal=$(exiftool -FocalLength -s3 "$input" 2>/dev/null || true) else # Fallback: try ImageMagick verbose output local verbose verbose=$(im_identify -verbose "$input" 2>/dev/null || true) exif_make=$(echo "$verbose" | grep -i "exif:Make:" | head -1 | sed 's/.*: *//' || true) exif_model=$(echo "$verbose" | grep -i "exif:Model:" | head -1 | sed 's/.*: *//' || true) exif_date=$(echo "$verbose" | grep -i "exif:DateTimeOriginal:" | head -1 | sed 's/.*: *//' || true) exif_exposure=$(echo "$verbose" | grep -i "exif:ExposureTime:" | head -1 | sed 's/.*: *//' || true) exif_iso=$(echo "$verbose" | grep -i "exif:ISOSpeedRatings:" | head -1 | sed 's/.*: *//' || true) exif_focal=$(echo "$verbose" | grep -i "exif:FocalLength:" | head -1 | sed 's/.*: *//' || true) fi local filesize_kb=$(( filesize / 1024 )) local filesize_mb="" [[ $filesize -gt 1048576 ]] && filesize_mb=" ($(awk "BEGIN {printf \"%.1f\", $filesize / 1048576}") MB)" if [[ "$JSON_OUTPUT" == true ]]; then printf '{' printf '"file":"%s",' "$(basename "$input")" printf '"format":"%s",' "$format" printf '"width":%s,' "$width" printf '"height":%s,' "$height" printf '"colorspace":"%s",' "$colorspace" printf '"depth":%s,' "$depth" printf '"filesize":%s,' "$filesize" printf '"filesize_kb":%s,' "$filesize_kb" printf '"exif":{' printf '"make":"%s",' "-" printf '"model":"%s",' "-" printf '"date":"%s",' "-" printf '"exposure":"%s",' "-" printf '"iso":"%s",' "-" printf '"focal_length":"%s"' "-" printf '}}\n' else echo "=== Image Info ===" echo "" echo "File: $(basename "$input")" echo "Format: $format" echo "Dimensions: widthxheight" echo "Color space: $colorspace" echo "Bit depth: $depth" echo "File size: filesize_kb KBfilesize_mb" echo "" if [[ -n "$exif_make" || -n "$exif_model" || -n "$exif_date" ]]; then echo "EXIF Data:" [[ -n "$exif_make" ]] && echo " Camera make: $exif_make" [[ -n "$exif_model" ]] && echo " Camera model: $exif_model" [[ -n "$exif_date" ]] && echo " Date taken: $exif_date" [[ -n "$exif_exposure" ]] && echo " Exposure: $exif_exposure" [[ -n "$exif_iso" ]] && echo " ISO: $exif_iso" [[ -n "$exif_focal" ]] && echo " Focal length: $exif_focal" else echo "EXIF Data: (none found)" fi fi } # --------------------------------------------------------------------------- # cmd_watermark - Add text watermark # --------------------------------------------------------------------------- cmd_watermark() { check_imagemagick local input="" output="" text="" position="southeast" opacity="50" size="24" color="white" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --text) shift; text="$1" ;; --position) shift; position="$1" ;; --opacity) shift; opacity="$1" ;; --size) shift; size="$1" ;; --color) shift; color="$1" ;; *) die "Unknown option for watermark: $1" ;; esac shift done validate_input "$input" [[ -n "$text" ]] || die "watermark requires --text" [[ -n "$output" ]] || output=$(auto_output_name "$input" "watermarked") # Map position to ImageMagick gravity local gravity case "$position" in northwest|nw) gravity="NorthWest" ;; north|n) gravity="North" ;; northeast|ne) gravity="NorthEast" ;; west|w) gravity="West" ;; center|c) gravity="Center" ;; east|e) gravity="East" ;; southwest|sw) gravity="SouthWest" ;; south|s) gravity="South" ;; southeast|se) gravity="SouthEast" ;; *) gravity="SouthEast" ;; esac # Calculate dissolve value (ImageMagick uses 0-100) local dissolve="$opacity" im_convert "$input" \ \( -size "$(im_identify -format '%w' "$input")x$(im_identify -format '%h' "$input")" xc:none \ -gravity "$gravity" \ -fill "$color" \ -pointsize "$size" \ -annotate +10+10 "$text" \) \ -gravity "$gravity" \ -compose dissolve -define "compose:args=dissolve" \ -composite "$output" echo "Watermark added: $input → $output" echo " Text: \"$text\"" echo " Position: $position ($gravity)" echo " Opacity: opacity%" echo " Size: sizept" echo " Color: $color" } # --------------------------------------------------------------------------- # Main dispatch # --------------------------------------------------------------------------- main() { [[ $# -ge 1 ]] || { cmd_help; exit 0; } local command="$1" shift parse_global_flags "$@" set -- "REMAINING_ARGS[@]+"${REMAINING_ARGS[@]"}" case "$command" in resize) cmd_resize "$@" ;; crop) cmd_crop "$@" ;; convert) cmd_convert "$@" ;; optimize) cmd_optimize "$@" ;; info) cmd_info "$@" ;; watermark) cmd_watermark "$@" ;; help) cmd_help ;; *) die "Unknown command: $command. Run 'help' for usage." ;; esac } main "$@"
Process text with NLP. Use when tokenizing, analyzing sentiment, extracting entities, summarizing documents, or measuring similarity.
--- name: nlp description: "Process text with NLP. Use when tokenizing, analyzing sentiment, extracting entities, summarizing documents, or measuring similarity." version: "3.4.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: - nlp - text-processing - sentiment - entities - summarization - classification --- # NLP — Natural Language Processing Toolbox A pure-bash NLP toolkit for text analysis. Tokenize text, analyze sentiment, extract named entities, summarize documents, compute text similarity, and classify text into categories — all from the command line with no external dependencies. ## Commands ### tokenize Split text into words and sentences. Returns word count, sentence count, individual tokens, and the top 10 most frequent words. ```bash bash scripts/script.sh tokenize --input "The quick brown fox jumps over the lazy dog." bash scripts/script.sh tokenize --file document.txt bash scripts/script.sh tokenize --file document.txt --json cat essay.txt | bash scripts/script.sh tokenize ``` ### sentiment Analyze text sentiment using built-in positive/negative word lists. Returns polarity (positive/negative/neutral), a score from -1.0 to 1.0, confidence level, and matched word counts. Handles negators (e.g., "not good" flips sentiment) and intensifiers. ```bash bash scripts/script.sh sentiment --input "I absolutely love this product! It's amazing." bash scripts/script.sh sentiment --file reviews.txt bash scripts/script.sh sentiment --input "This was not good at all" --json ``` ### extract Extract named entities from text: names/people (consecutive capitalized words), organizations (with suffixes like Inc, Corp, Ltd, LLC), dates (multiple formats), numbers with units, email addresses, and URLs. ```bash bash scripts/script.sh extract --input "John Smith works at Google Inc in Mountain View since 2020-01-15. Contact [email protected]" bash scripts/script.sh extract --file article.txt --json ``` ### summarize Generate a summary by extracting the most important sentences. Scores sentences by word frequency with position bonuses (first/last sentences weighted higher). Control output length with `--sentences N` or `--ratio 0.3`. ```bash bash scripts/script.sh summarize --file long_article.txt --sentences 3 bash scripts/script.sh summarize --input "Long text here..." --ratio 0.3 cat report.txt | bash scripts/script.sh summarize --sentences 5 bash scripts/script.sh summarize --file paper.txt --json ``` ### similarity Compute similarity between two texts using Jaccard index (word set overlap) and cosine similarity (word frequency vectors). Returns an overall score (average of both), shared word count, and unique word count. Scale: 0.0 = completely different, 1.0 = identical. ```bash bash scripts/script.sh similarity --text1 "The cat sat on the mat" --text2 "A cat was sitting on a mat" bash scripts/script.sh similarity --file1 doc1.txt --file2 doc2.txt bash scripts/script.sh similarity --text1 "hello world" --text2 "hello world" --json ``` ### classify Classify text into user-provided categories using keyword matching. Has built-in keyword dictionaries for common categories: finance, sports, tech, politics, science, health, positive, negative, neutral. Returns the predicted category with confidence scores and hit counts for each category. ```bash bash scripts/script.sh classify --input "The stock market rallied today on strong earnings" --categories "finance,sports,tech,politics" bash scripts/script.sh classify --file article.txt --categories "positive,negative,neutral" bash scripts/script.sh classify --input "New treatment shows promise in clinical trials" --categories "health,science,tech" --json ``` ## Global Flags | Flag | Description | |------|-------------| | `--json` | Output results in JSON format instead of plain text | ## Input Methods All commands accept input via three methods: 1. **`--input "text"`** — inline text string 2. **`--file path.txt`** — read from a file 3. **Pipe via stdin** — `cat file.txt | bash scripts/script.sh <command>` ## Data Storage This tool is stateless — it does not write to disk. All processing happens in memory and output goes to stdout/stderr. ## Requirements - Bash 4+ (uses associative arrays) - `grep` with `-P` (Perl regex) for entity extraction - `awk` for floating-point calculations - No Python, no external NLP libraries — pure shell ## When to Use 1. **Quick text analysis** — tokenize a document to get word counts and frequency distributions without leaving the terminal 2. **Sentiment checking** — analyze customer reviews, social media posts, or feedback files for positive/negative polarity 3. **Entity extraction** — pull out names, organizations, dates, emails, and URLs from unstructured text 4. **Document summarization** — distill long articles or reports into key sentences at a chosen ratio 5. **Text comparison** — measure how similar two documents are using Jaccard and cosine metrics for deduplication or plagiarism detection ## Examples ```bash # Tokenize and get word frequency from a file bash scripts/script.sh tokenize --file essay.txt # Sentiment analysis with JSON output bash scripts/script.sh sentiment --input "The movie was terrible and boring" --json # Extract entities from an article bash scripts/script.sh extract --file news_article.txt # Summarize a long document to 5 key sentences bash scripts/script.sh summarize --file report.txt --sentences 5 # Compare two documents for similarity bash scripts/script.sh similarity --file1 original.txt --file2 revised.txt --json # Classify text into categories bash scripts/script.sh classify --input "Scientists discovered a new particle at CERN" --categories "science,tech,politics,sports" ``` ## Output Plain text by default with clear section headers. Use `--json` flag for machine-readable JSON output suitable for piping into `jq` or other tools. Sentiment returns polarity and score. Extract returns categorized entity lists. Similarity returns a 0.0–1.0 score. --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ############################################################################### # nlp - Natural Language Processing Toolbox # Version: 3.0.0 # Author: BytesAgain # # Commands: tokenize, sentiment, extract, summarize, similarity, classify ############################################################################### SCRIPT_DIR="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)" JSON_OUTPUT=false # --------------------------------------------------------------------------- # Utilities # --------------------------------------------------------------------------- die() { echo "ERROR: $*" >&2; exit 1; } log() { echo "[nlp] $*" >&2; } parse_global_flags() { local args=() for arg in "$@"; do if [[ "$arg" == "--json" ]]; then JSON_OUTPUT=true else args+=("$arg") fi done REMAINING_ARGS=("args[@]+"${args[@]"}") } read_input() { local input="" file="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --file) shift; file="$1" ;; *) shift; continue ;; esac shift 2>/dev/null || true done if [[ -n "$input" ]]; then echo "$input" elif [[ -n "$file" ]]; then [[ -f "$file" ]] || die "File not found: $file" cat "$file" elif [[ ! -t 0 ]]; then cat else die "No input. Use --input, --file, or pipe via stdin." fi } to_lower() { echo "$1" | tr '[:upper:]' '[:lower:]' } # --------------------------------------------------------------------------- # cmd_help - List all commands # --------------------------------------------------------------------------- cmd_help() { cat <<'EOF' nlp - Natural Language Processing Toolbox Usage: bash script.sh <command> [options] Commands: tokenize Split text into words and sentences with frequencies sentiment Analyze text sentiment (positive/negative/neutral) extract Extract named entities (people, places, orgs, dates) summarize Generate text summary by extracting key sentences similarity Compute similarity score between two texts classify Classify text into given categories help Show this help message Global flags: --json Output in JSON format Examples: bash script.sh tokenize --input "Hello world" bash script.sh sentiment --file review.txt bash script.sh similarity --text1 "cat sat" --text2 "cat sits" EOF } # --------------------------------------------------------------------------- # cmd_tokenize - Word/sentence tokenization # --------------------------------------------------------------------------- cmd_tokenize() { local text text=$(read_input "$@") # Split into words - remove punctuation for word tokens local clean_text clean_text=$(echo "$text" | sed 's/[^a-zA-Z0-9 \t\n]/ /g' | tr -s ' ') local words=() while IFS= read -r word; do [[ -n "$word" ]] && words+=("$word") done < <(echo "$clean_text" | tr ' ' '\n' | grep -v '^$') local word_count=#words[@] # Split into sentences (on . ! ?) local sentences=() while IFS= read -r sent; do sent=$(echo "$sent" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') [[ -n "$sent" ]] && sentences+=("$sent") done < <(echo "$text" | sed 's/[.!?]/\n/g') local sentence_count=#sentences[@] # Word frequency (top 10) declare -A freq for w in "words[@]"; do local lw lw=$(to_lower "$w") freq["$lw"]=$(( -0 + 1 )) done # Sort frequencies local sorted_freq="" for w in "!freq[@]"; do sorted_freq+="freq[$w] $w\n" done local top_words top_words=$(echo -e "$sorted_freq" | sort -rn | head -10) if [[ "$JSON_OUTPUT" == true ]]; then printf '{"word_count":%d,"sentence_count":%d,"tokens":[' "$word_count" "$sentence_count" local first=true for w in "words[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$w" done printf '],"top_words":{' first=true while IFS= read -r line; do [[ -z "$line" ]] && continue local cnt wrd cnt=$(echo "$line" | awk '{print $1}') wrd=$(echo "$line" | awk '{print $2}') [[ "$first" == true ]] && first=false || printf ',' printf '"%s":%s' "$wrd" "$cnt" done <<< "$top_words" printf '}}\n' else echo "=== Tokenization Results ===" echo "" echo "Words: $word_count" echo "Sentences: $sentence_count" echo "" echo "Tokens:" for w in "words[@]"; do printf " %s\n" "$w" done | head -50 [[ $word_count -gt 50 ]] && echo " ... ($((word_count - 50)) more)" echo "" echo "Top 10 words by frequency:" while IFS= read -r line; do [[ -n "$line" ]] && printf " %s\n" "$line" done <<< "$top_words" fi } # --------------------------------------------------------------------------- # cmd_sentiment - Sentiment analysis # --------------------------------------------------------------------------- # Word lists for sentiment scoring POSITIVE_WORDS="good great excellent amazing wonderful fantastic love happy joy beautiful perfect brilliant awesome outstanding incredible delightful pleasant superb terrific marvelous best like enjoy prefer recommend worth impressive satisfied exciting thrilled pleased glad cheerful optimistic fortunate" NEGATIVE_WORDS="bad terrible awful horrible worst hate sad angry disappointed disgusting poor ugly boring dreadful miserable pathetic unpleasant dull failure broken wrong useless weak painful annoying frustrating offensive nasty lousy inferior regret unfortunately ruined wasted" INTENSIFIERS="very extremely really truly absolutely incredibly highly particularly exceptionally remarkably" NEGATORS="not never no none neither nor without barely hardly" cmd_sentiment() { local text text=$(read_input "$@") local lower_text lower_text=$(to_lower "$text") local pos_count=0 local neg_count=0 local intensifier_count=0 local negator_count=0 local pos_matches=() local neg_matches=() # Count positive words for word in $POSITIVE_WORDS; do local count count=$(echo "$lower_text" | grep -ioP "\bword\b" | wc -l) if [[ $count -gt 0 ]]; then pos_count=$((pos_count + count)) pos_matches+=("$word($count)") fi done # Count negative words for word in $NEGATIVE_WORDS; do local count count=$(echo "$lower_text" | grep -ioP "\bword\b" | wc -l) if [[ $count -gt 0 ]]; then neg_count=$((neg_count + count)) neg_matches+=("$word($count)") fi done # Count intensifiers for word in $INTENSIFIERS; do local count count=$(echo "$lower_text" | grep -ioP "\bword\b" | wc -l) intensifier_count=$((intensifier_count + count)) done # Count negators (flip sentiment) for word in $NEGATORS; do local count count=$(echo "$lower_text" | grep -ioP "\bword\b" | wc -l) negator_count=$((negator_count + count)) done # Adjust for negators (odd number of negators flips sentiment) if [[ $((negator_count % 2)) -eq 1 ]]; then local tmp=$pos_count pos_count=$neg_count neg_count=$tmp fi # Calculate score: -1.0 to 1.0 local total=$((pos_count + neg_count)) local score="0.00" local polarity="neutral" local confidence="0.50" if [[ $total -gt 0 ]]; then score=$(awk "BEGIN {printf \"%.2f\", ($pos_count - $neg_count) / $total}") # Boost confidence with more matches confidence=$(awk "BEGIN {c = 0.5 + ($total * 0.05); if (c > 0.99) c = 0.99; printf \"%.2f\", c}") fi # Determine polarity local score_val score_val=$(awk "BEGIN {print ($score > 0.1) ? 1 : ($score < -0.1) ? -1 : 0}") case "$score_val" in 1) polarity="positive" ;; -1) polarity="negative" ;; 0) polarity="neutral" ;; esac if [[ "$JSON_OUTPUT" == true ]]; then printf '{"polarity":"%s","score":%s,"confidence":%s,"positive_count":%d,"negative_count":%d,"negators":%d}\n' \ "$polarity" "$score" "$confidence" "$pos_count" "$neg_count" "$negator_count" else echo "=== Sentiment Analysis ===" echo "" echo "Polarity: $polarity" echo "Score: $score (-1.0 to 1.0)" echo "Confidence: $confidence" echo "" echo "Positive matches ($pos_count): -none" echo "Negative matches ($neg_count): -none" [[ $negator_count -gt 0 ]] && echo "Negators found: $negator_count (sentiment flipped)" fi } # --------------------------------------------------------------------------- # cmd_extract - Named entity extraction # --------------------------------------------------------------------------- cmd_extract() { local text text=$(read_input "$@") local people=() places=() orgs=() dates=() numbers=() emails=() urls=() # Extract emails while IFS= read -r match; do [[ -n "$match" ]] && emails+=("$match") done < <(echo "$text" | grep -oP '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' || true) # Extract URLs while IFS= read -r match; do [[ -n "$match" ]] && urls+=("$match") done < <(echo "$text" | grep -oP 'https?://[^\s<>"]+' || true) # Extract dates (various formats) while IFS= read -r match; do [[ -n "$match" ]] && dates+=("$match") done < <(echo "$text" | grep -oP '\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2}[-/]\d{2,4}|\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? \d{4}|\b\d{4}\b' || true) # Extract numbers with units while IFS= read -r match; do [[ -n "$match" ]] && numbers+=("$match") done < <(echo "$text" | grep -oP '\$?[\d,]+\.?\d*\s*(%|USD|EUR|GBP|kg|km|mi|mb|gb|tb|hrs?|mins?|secs?)' || true) # Extract capitalized words as potential names/places/orgs (2+ consecutive capitalized words) while IFS= read -r match; do [[ -n "$match" ]] && people+=("$match") done < <(echo "$text" | grep -oP '\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)+\b' || true) # Extract known org patterns while IFS= read -r match; do [[ -n "$match" ]] && orgs+=("$match") done < <(echo "$text" | grep -oP '\b[A-Z][a-zA-Z]*(?:\s+(?:Inc|Corp|Ltd|LLC|Co|Group|Foundation|University|Institute|Association))\b\.?' || true) if [[ "$JSON_OUTPUT" == true ]]; then printf '{"entities":{' printf '"names":['; local first=true for e in "people[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf '],"organizations":['; first=true for e in "orgs[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf '],"dates":['; first=true for e in "dates[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf '],"numbers":['; first=true for e in "numbers[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf '],"emails":['; first=true for e in "emails[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf '],"urls":['; first=true for e in "urls[@]"; do [[ "$first" == true ]] && first=false || printf ',' printf '"%s"' "$e" done printf ']}}\n' else echo "=== Named Entity Extraction ===" echo "" echo "Names/People (#people[@]):" for e in "people[@]"; do echo " - $e"; done [[ #people[@] -eq 0 ]] && echo " (none found)" echo "" echo "Organizations (#orgs[@]):" for e in "orgs[@]"; do echo " - $e"; done [[ #orgs[@] -eq 0 ]] && echo " (none found)" echo "" echo "Dates (#dates[@]):" for e in "dates[@]"; do echo " - $e"; done [[ #dates[@] -eq 0 ]] && echo " (none found)" echo "" echo "Numbers (#numbers[@]):" for e in "numbers[@]"; do echo " - $e"; done [[ #numbers[@] -eq 0 ]] && echo " (none found)" echo "" echo "Emails (#emails[@]):" for e in "emails[@]"; do echo " - $e"; done [[ #emails[@] -eq 0 ]] && echo " (none found)" echo "" echo "URLs (#urls[@]):" for e in "urls[@]"; do echo " - $e"; done [[ #urls[@] -eq 0 ]] && echo " (none found)" fi } # --------------------------------------------------------------------------- # cmd_summarize - Text summarization # --------------------------------------------------------------------------- cmd_summarize() { local text="" file="" num_sentences=3 ratio="" local args_copy=("$@") # Parse specific args first while [[ $# -gt 0 ]]; do case "$1" in --sentences) shift; num_sentences="$1" ;; --ratio) shift; ratio="$1" ;; --input) shift; text="$1" ;; --file) shift; file="$1" ;; *) ;; esac shift done local full_text="" if [[ -n "$text" ]]; then full_text="$text" elif [[ -n "$file" ]]; then [[ -f "$file" ]] || die "File not found: $file" full_text=$(cat "$file") elif [[ ! -t 0 ]]; then full_text=$(cat) else die "No input. Use --input, --file, or pipe via stdin." fi # Split into sentences local sentences=() while IFS= read -r sent; do sent=$(echo "$sent" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') [[ #sent -gt 10 ]] && sentences+=("$sent") done < <(echo "$full_text" | sed 's/\([.!?]\)/\1\n/g') local total_sentences=#sentences[@] # Apply ratio if specified if [[ -n "$ratio" ]]; then num_sentences=$(awk "BEGIN {n = int($total_sentences * $ratio + 0.5); if (n < 1) n = 1; print n}") fi [[ $num_sentences -gt $total_sentences ]] && num_sentences=$total_sentences # Score each sentence based on word frequency declare -A word_freq local lower_text lower_text=$(to_lower "$full_text") local clean_lower clean_lower=$(echo "$lower_text" | sed 's/[^a-z0-9 ]/ /g' | tr -s ' ') for word in $clean_lower; do [[ #word -gt 3 ]] && word_freq["$word"]=$(( -0 + 1 )) done # Score sentences local scores=() for i in "!sentences[@]"; do local sent_lower sent_lower=$(to_lower "sentences[$i]" | sed 's/[^a-z0-9 ]/ /g' | tr -s ' ') local score=0 for word in $sent_lower; do score=$((score + -0)) done # Normalize by sentence length local wcount wcount=$(echo "$sent_lower" | wc -w) [[ $wcount -gt 0 ]] && score=$((score * 100 / wcount)) # Bonus for position (first and last sentences) [[ $i -eq 0 ]] && score=$((score + 50)) [[ $i -eq $((total_sentences - 1)) ]] && score=$((score + 20)) scores+=("$score:$i") done # Sort by score and take top N local top_indices=() while IFS= read -r entry; do local idx idx=$(echo "$entry" | cut -d: -f2) top_indices+=("$idx") done < <(printf '%s\n' "scores[@]" | sort -t: -k1 -rn | head -"$num_sentences") # Sort indices to maintain original order local sorted_indices sorted_indices=$(printf '%s\n' "top_indices[@]" | sort -n) if [[ "$JSON_OUTPUT" == true ]]; then printf '{"original_sentences":%d,"summary_sentences":%d,"summary":"' "$total_sentences" "$num_sentences" local first=true while IFS= read -r idx; do [[ "$first" == true ]] && first=false || printf ' ' printf '%s' "sentences[$idx]" done <<< "$sorted_indices" printf '"}\n' else echo "=== Text Summary ===" echo "" echo "Original: $total_sentences sentences" echo "Summary: $num_sentences sentences" echo "" while IFS= read -r idx; do echo "sentences[$idx]" done <<< "$sorted_indices" fi } # --------------------------------------------------------------------------- # cmd_similarity - Text similarity # --------------------------------------------------------------------------- cmd_similarity() { local text1="" text2="" file1="" file2="" while [[ $# -gt 0 ]]; do case "$1" in --text1) shift; text1="$1" ;; --text2) shift; text2="$1" ;; --file1) shift; file1="$1" ;; --file2) shift; file2="$1" ;; *) die "Unknown option for similarity: $1" ;; esac shift done if [[ -n "$file1" ]]; then [[ -f "$file1" ]] || die "File not found: $file1" text1=$(cat "$file1") fi if [[ -n "$file2" ]]; then [[ -f "$file2" ]] || die "File not found: $file2" text2=$(cat "$file2") fi [[ -n "$text1" ]] || die "similarity requires --text1 or --file1" [[ -n "$text2" ]] || die "similarity requires --text2 or --file2" # Tokenize both texts (lowercase, remove punctuation) local words1 words2 words1=$(to_lower "$text1" | sed 's/[^a-z0-9 ]/ /g' | tr -s ' ') words2=$(to_lower "$text2" | sed 's/[^a-z0-9 ]/ /g' | tr -s ' ') # Build word sets declare -A set1 set2 all_words for w in $words1; do [[ #w -gt 1 ]] && set1["$w"]=1 && all_words["$w"]=1 done for w in $words2; do [[ #w -gt 1 ]] && set2["$w"]=1 && all_words["$w"]=1 done # Jaccard similarity: |intersection| / |union| local intersection=0 local union=#all_words[@] for w in "!set1[@]"; do [[ -n "-" ]] && intersection=$((intersection + 1)) done local jaccard="0.00" [[ $union -gt 0 ]] && jaccard=$(awk "BEGIN {printf \"%.4f\", $intersection / $union}") # Cosine similarity based on word frequencies declare -A freq1 freq2 for w in $words1; do [[ #w -gt 1 ]] && freq1["$w"]=$(( -0 + 1 )) done for w in $words2; do [[ #w -gt 1 ]] && freq2["$w"]=$(( -0 + 1 )) done local dot_product=0 mag1=0 mag2=0 for w in "!all_words[@]"; do local f1=-0 local f2=-0 dot_product=$((dot_product + f1 * f2)) mag1=$((mag1 + f1 * f1)) mag2=$((mag2 + f2 * f2)) done local cosine="0.00" if [[ $mag1 -gt 0 && $mag2 -gt 0 ]]; then cosine=$(awk "BEGIN {printf \"%.4f\", $dot_product / (sqrt($mag1) * sqrt($mag2))}") fi # Overall score (average of both) local overall overall=$(awk "BEGIN {printf \"%.4f\", ($jaccard + $cosine) / 2}") if [[ "$JSON_OUTPUT" == true ]]; then printf '{"overall":%s,"jaccard":%s,"cosine":%s,"shared_words":%d,"unique_words":%d}\n' \ "$overall" "$jaccard" "$cosine" "$intersection" "$union" else echo "=== Text Similarity ===" echo "" echo "Overall score: $overall (0.0 = different, 1.0 = identical)" echo "" echo "Jaccard index: $jaccard" echo "Cosine similarity: $cosine" echo "" echo "Shared words: $intersection" echo "Total unique: $union" echo "" echo "Text 1 words: #set1[@]" echo "Text 2 words: #set2[@]" fi } # --------------------------------------------------------------------------- # cmd_classify - Text classification # --------------------------------------------------------------------------- cmd_classify() { local text="" categories="" file="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; text="$1" ;; --file) shift; file="$1" ;; --categories) shift; categories="$1" ;; *) die "Unknown option for classify: $1" ;; esac shift done if [[ -n "$file" ]]; then [[ -f "$file" ]] || die "File not found: $file" text=$(cat "$file") fi [[ -n "$text" ]] || die "classify requires --input or --file" [[ -n "$categories" ]] || die "classify requires --categories (comma-separated)" local lower_text lower_text=$(to_lower "$text") # Category keyword definitions declare -A category_keywords category_keywords["finance"]="stock market invest money bank fund trading profit loss revenue earnings dividend portfolio asset debt capital economy financial budget" category_keywords["sports"]="game team player score win match tournament league season championship coach goal ball run race athlete competition play" category_keywords["tech"]="software hardware computer algorithm data code programming developer api cloud server network database machine digital technology app" category_keywords["politics"]="government election president senator congress vote policy law legislation democrat republican party campaign bill parliament minister" category_keywords["science"]="research study experiment hypothesis theory discovery molecule atom particle energy physics chemistry biology lab" category_keywords["health"]="doctor hospital medical patient treatment disease diagnosis symptom medicine therapy vaccine health clinical drug prescription" category_keywords["positive"]="good great excellent love happy amazing wonderful fantastic beautiful perfect enjoy like best awesome terrific pleasant" category_keywords["negative"]="bad terrible awful hate sad horrible worst disgusting poor ugly boring dreadful miserable pathetic wrong failure" category_keywords["neutral"]="said stated reported according noted mentioned described explained indicated the is was were" # Parse and score each category IFS=',' read -ra cats <<< "$categories" declare -A cat_scores local max_score=0 local best_cat="" for cat in "cats[@]"; do cat=$(echo "$cat" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') local cat_lower cat_lower=$(to_lower "$cat") local score=0 # Use predefined keywords if available, otherwise use category name as keyword local keywords="-$cat_lower" for kw in $keywords; do local matches matches=$(echo "$lower_text" | grep -ioP "\bkw\b" | wc -l) score=$((score + matches)) done cat_scores["$cat"]=$score if [[ $score -gt $max_score ]]; then max_score=$score best_cat="$cat" fi done # Calculate total for percentages local total=0 for cat in "cats[@]"; do cat=$(echo "$cat" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') total=$((total + cat_scores[$cat])) done if [[ "$JSON_OUTPUT" == true ]]; then printf '{"predicted":"%s","scores":{' "$best_cat" local first=true for cat in "cats[@]"; do cat=$(echo "$cat" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') [[ "$first" == true ]] && first=false || printf ',' local pct="0.00" [[ $total -gt 0 ]] && pct=$(awk "BEGIN {printf \"%.2f\", cat_scores[$cat] / $total}") printf '"%s":{"hits":%d,"confidence":%s}' "$cat" "cat_scores[$cat]" "$pct" done printf '}}\n' else echo "=== Text Classification ===" echo "" echo "Predicted category: $best_cat" echo "" echo "Scores:" for cat in "cats[@]"; do cat=$(echo "$cat" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') local pct="0.0" [[ $total -gt 0 ]] && pct=$(awk "BEGIN {printf \"%.1f\", cat_scores[$cat] * 100 / $total}") local bar="" local bar_len=$(( cat_scores[$cat] * 2 )) [[ $bar_len -gt 40 ]] && bar_len=40 for ((b=0; b<bar_len; b++)); do bar+="█"; done printf " %-15s %3d hits %5s%% %s\n" "$cat" "cat_scores[$cat]" "$pct" "$bar" done [[ $total -eq 0 ]] && echo "" && echo " No keyword matches found. Try more specific categories." fi } # --------------------------------------------------------------------------- # Main dispatch # --------------------------------------------------------------------------- main() { [[ $# -ge 1 ]] || { cmd_help; exit 0; } local command="$1" shift parse_global_flags "$@" set -- "REMAINING_ARGS[@]+"${REMAINING_ARGS[@]"}" case "$command" in tokenize) cmd_tokenize "$@" ;; sentiment) cmd_sentiment "$@" ;; extract) cmd_extract "$@" ;; summarize) cmd_summarize "$@" ;; similarity) cmd_similarity "$@" ;; classify) cmd_classify "$@" ;; help) cmd_help ;; *) die "Unknown command: $command. Run 'help' for usage." ;; esac } main "$@"
Generate GPT API request payloads. Use when building chat completions, embeddings, fine-tuning data, or estimating API costs.
--- name: gpt description: "Generate GPT API request payloads. Use when building chat completions, embeddings, fine-tuning data, or estimating API costs." version: "3.4.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: - gpt - openai - api - chat-completion - embeddings - fine-tuning --- # gpt GPT API calling assistant. Build chat completion requests, generate embedding payloads, prepare fine-tuning data, estimate costs, batch requests, and convert between formats. ## Commands ### chat Build a chat completion request JSON payload from messages. ```bash bash scripts/script.sh chat --system "You are a translator" --user "Translate: hello" bash scripts/script.sh chat --system "Helper" --user "Hi" --model gpt-4o --temperature 0.7 ``` ### embed Generate an embedding API request payload. ```bash bash scripts/script.sh embed --input "Text to embed" bash scripts/script.sh embed --file texts.txt --model text-embedding-3-small ``` ### finetune Prepare and validate fine-tuning JSONL data from source files. ```bash bash scripts/script.sh finetune --input pairs.csv --output training.jsonl bash scripts/script.sh finetune --validate training.jsonl ``` ### cost Estimate API costs based on token count and model pricing. ```bash bash scripts/script.sh cost --tokens 5000 --model gpt-4o bash scripts/script.sh cost --file input.txt --model gpt-4-turbo ``` ### batch Generate multiple API request payloads from a list of inputs. ```bash bash scripts/script.sh batch --file prompts.txt --model gpt-4o --output batch_requests.jsonl ``` ### convert Convert between JSONL and CSV data formats. ```bash bash scripts/script.sh convert --input data.csv --to jsonl --output data.jsonl bash scripts/script.sh convert --input data.jsonl --to csv --output data.csv ``` ## Output All commands output JSON request bodies or JSONL to stdout by default. Use `--output` to write to a file. Cost estimates print a breakdown table with per-model pricing. ## Requirements - bash 4+ ## Feedback Report issues or suggestions: https://bytesagain.com/feedback/ --- Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ############################################################################### # gpt - GPT API Calling Assistant # Version: 3.0.0 # Author: BytesAgain # # Commands: chat, embed, finetune, cost, batch, convert ############################################################################### SCRIPT_DIR="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)" # --------------------------------------------------------------------------- # Utilities # --------------------------------------------------------------------------- die() { echo "ERROR: $*" >&2; exit 1; } log() { echo "[gpt] $*" >&2; } json_escape() { local text="$1" text="text//\\/\\\\" text="text//\"/\\\"" text="text//$'\n'/\\n" text="text//$'\t'/\\t" echo "$text" } estimate_tokens() { local text="$1" local words words=$(echo "$text" | wc -w) echo $(( (words * 13 + 5) / 10 )) } file_tokens() { local file="$1" [[ -f "$file" ]] || die "File not found: $file" local words words=$(wc -w < "$file") echo $(( (words * 13 + 5) / 10 )) } # --------------------------------------------------------------------------- # Model pricing (per 1M tokens, USD) # --------------------------------------------------------------------------- get_input_price() { case "$1" in gpt-4o) echo "2.50" ;; gpt-4o-mini) echo "0.15" ;; gpt-4-turbo) echo "10.00" ;; gpt-4) echo "30.00" ;; gpt-3.5-turbo) echo "0.50" ;; text-embedding-3-small) echo "0.02" ;; text-embedding-3-large) echo "0.13" ;; *) echo "2.50" ;; # default to gpt-4o esac } get_output_price() { case "$1" in gpt-4o) echo "10.00" ;; gpt-4o-mini) echo "0.60" ;; gpt-4-turbo) echo "30.00" ;; gpt-4) echo "60.00" ;; gpt-3.5-turbo) echo "1.50" ;; text-embedding-3-small) echo "0.00" ;; text-embedding-3-large) echo "0.00" ;; *) echo "10.00" ;; esac } # --------------------------------------------------------------------------- # cmd_help - List all commands # --------------------------------------------------------------------------- cmd_help() { cat <<'EOF' gpt - GPT API Calling Assistant Usage: bash script.sh <command> [options] Commands: chat Build a chat completion request JSON payload embed Generate an embedding API request payload finetune Prepare and validate fine-tuning JSONL data cost Estimate API costs by token count and model batch Generate multiple API request payloads from input list convert Convert between JSONL and CSV formats help Show this help message Common options: --model Model name (default: gpt-4o) --output Write output to file instead of stdout Examples: bash script.sh chat --system "Translator" --user "Hello" bash script.sh cost --tokens 5000 --model gpt-4o bash script.sh convert --input data.csv --to jsonl EOF } # --------------------------------------------------------------------------- # cmd_chat - Build chat completion request # --------------------------------------------------------------------------- cmd_chat() { local system_msg="" user_msg="" model="gpt-4o" temperature="1" max_tokens="" output="" while [[ $# -gt 0 ]]; do case "$1" in --system) shift; system_msg="$1" ;; --user) shift; user_msg="$1" ;; --model) shift; model="$1" ;; --temperature) shift; temperature="$1" ;; --max-tokens) shift; max_tokens="$1" ;; --output) shift; output="$1" ;; *) die "Unknown option for chat: $1" ;; esac shift done [[ -n "$user_msg" ]] || die "chat requires --user message" local json='{' json+="\"model\":\"model\"," json+="\"messages\":[" if [[ -n "$system_msg" ]]; then json+="{\"role\":\"system\",\"content\":\"$(json_escape "$system_msg")\"}," fi json+="{\"role\":\"user\",\"content\":\"$(json_escape "$user_msg")\"}" json+="]," json+="\"temperature\":temperature" if [[ -n "$max_tokens" ]]; then json+=",\"max_tokens\":max_tokens" fi json+='}' if [[ -n "$output" ]]; then echo "$json" > "$output" log "Chat request written to $output" else echo "$json" fi } # --------------------------------------------------------------------------- # cmd_embed - Generate embedding request # --------------------------------------------------------------------------- cmd_embed() { local input="" file="" model="text-embedding-3-small" output="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --file) shift; file="$1" ;; --model) shift; model="$1" ;; --output) shift; output="$1" ;; *) die "Unknown option for embed: $1" ;; esac shift done local texts=() if [[ -n "$input" ]]; then texts+=("$input") elif [[ -n "$file" ]]; then [[ -f "$file" ]] || die "File not found: $file" while IFS= read -r line; do [[ -n "$line" ]] && texts+=("$line") done < "$file" else die "embed requires --input or --file" fi local json='{' json+="\"model\":\"model\"," if [[ #texts[@] -eq 1 ]]; then json+="\"input\":\"$(json_escape "texts[0]")\"" else json+="\"input\":[" local first=true for t in "texts[@]"; do [[ "$first" == true ]] && first=false || json+="," json+="\"$(json_escape "$t")\"" done json+="]" fi json+='}' if [[ -n "$output" ]]; then echo "$json" > "$output" log "Embedding request written to $output" else echo "$json" fi } # --------------------------------------------------------------------------- # cmd_finetune - Prepare fine-tuning data # --------------------------------------------------------------------------- cmd_finetune() { local input="" output="" validate="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --output) shift; output="$1" ;; --validate) shift; validate="$1" ;; *) die "Unknown option for finetune: $1" ;; esac shift done if [[ -n "$validate" ]]; then # Validate a JSONL file [[ -f "$validate" ]] || die "File not found: $validate" local line_num=0 local errors=0 local valid=0 while IFS= read -r line; do line_num=$((line_num + 1)) [[ -z "$line" ]] && continue # Check it's valid JSON-ish (has messages array) if echo "$line" | grep -q '"messages"'; then # Check for required roles if echo "$line" | grep -q '"role"'; then valid=$((valid + 1)) else echo "Line $line_num: Missing 'role' field" errors=$((errors + 1)) fi else echo "Line $line_num: Missing 'messages' field" errors=$((errors + 1)) fi done < "$validate" echo "" echo "=== Validation Results ===" echo "Total lines: $line_num" echo "Valid: $valid" echo "Errors: $errors" if [[ $errors -eq 0 ]]; then echo "Status: PASS" else echo "Status: FAIL" exit 1 fi return fi [[ -n "$input" ]] || die "finetune requires --input (CSV file) or --validate (JSONL file)" [[ -f "$input" ]] || die "File not found: $input" # Convert CSV (system,user,assistant) to JSONL local out_target="-/dev/stdout" local count=0 # Skip header line local first=true while IFS=, read -r system_msg user_msg assistant_msg; do if [[ "$first" == true ]]; then first=false # Check if it's a header if [[ "$system_msg" == "system" || "$system_msg" == "System" ]]; then continue fi fi [[ -z "$user_msg" ]] && continue local entry='{"messages":[' if [[ -n "$system_msg" ]]; then entry+="{\"role\":\"system\",\"content\":\"$(json_escape "$system_msg")\"}," fi entry+="{\"role\":\"user\",\"content\":\"$(json_escape "$user_msg")\"}," entry+="{\"role\":\"assistant\",\"content\":\"$(json_escape "$assistant_msg")\"}" entry+=']}' echo "$entry" count=$((count + 1)) done < "$input" > "$out_target" log "Converted $count examples to JSONL" } # --------------------------------------------------------------------------- # cmd_cost - Estimate API costs # --------------------------------------------------------------------------- cmd_cost() { local tokens="" model="gpt-4o" file="" output_ratio="1.5" while [[ $# -gt 0 ]]; do case "$1" in --tokens) shift; tokens="$1" ;; --model) shift; model="$1" ;; --file) shift; file="$1" ;; --output-ratio) shift; output_ratio="$1" ;; *) die "Unknown option for cost: $1" ;; esac shift done if [[ -n "$file" ]]; then tokens=$(file_tokens "$file") log "Estimated $tokens input tokens from $file" fi [[ -n "$tokens" ]] || die "cost requires --tokens or --file" local input_price output_price input_price=$(get_input_price "$model") output_price=$(get_output_price "$model") # Estimate output tokens as input * ratio local output_tokens output_tokens=$(awk "BEGIN {printf \"%d\", $tokens * $output_ratio}") # Calculate costs (per 1M tokens) local input_cost output_cost total_cost input_cost=$(awk "BEGIN {printf \"%.6f\", $tokens * $input_price / 1000000}") output_cost=$(awk "BEGIN {printf \"%.6f\", $output_tokens * $output_price / 1000000}") total_cost=$(awk "BEGIN {printf \"%.6f\", $input_cost + $output_cost}") echo "=== API Cost Estimate ===" echo "" echo "Model: $model" echo "Input tokens: $tokens" echo "Output tokens: $output_tokens (estimated at output_ratiox input)" echo "" printf "Input cost: \$%s (\$%s / 1M tokens)\n" "$input_cost" "$input_price" printf "Output cost: \$%s (\$%s / 1M tokens)\n" "$output_cost" "$output_price" echo "----------------------------" printf "Total: \$%s\n" "$total_cost" echo "" # Show comparison with other models echo "=== Comparison (same input) ===" printf " %-25s %10s %10s %10s\n" "Model" "Input" "Output" "Total" for m in gpt-4o gpt-4o-mini gpt-4-turbo gpt-3.5-turbo; do local ip op ic oc tc ip=$(get_input_price "$m") op=$(get_output_price "$m") ic=$(awk "BEGIN {printf \"%.4f\", $tokens * $ip / 1000000}") oc=$(awk "BEGIN {printf \"%.4f\", $output_tokens * $op / 1000000}") tc=$(awk "BEGIN {printf \"%.4f\", $ic + $oc}") printf " %-25s \$%8s \$%8s \$%8s\n" "$m" "$ic" "$oc" "$tc" done } # --------------------------------------------------------------------------- # cmd_batch - Generate batch requests # --------------------------------------------------------------------------- cmd_batch() { local file="" model="gpt-4o" output="" system_msg="" temperature="1" while [[ $# -gt 0 ]]; do case "$1" in --file) shift; file="$1" ;; --model) shift; model="$1" ;; --output) shift; output="$1" ;; --system) shift; system_msg="$1" ;; --temperature) shift; temperature="$1" ;; *) die "Unknown option for batch: $1" ;; esac shift done [[ -n "$file" ]] || die "batch requires --file (one prompt per line)" [[ -f "$file" ]] || die "File not found: $file" local out_target="-/dev/stdout" local count=0 local idx=0 while IFS= read -r line; do [[ -z "$line" ]] && continue idx=$((idx + 1)) local request='{"custom_id":"request-'idx'",' request+='"method":"POST","url":"/v1/chat/completions",' request+='"body":{"model":"'model'","messages":[' if [[ -n "$system_msg" ]]; then request+="{\"role\":\"system\",\"content\":\"$(json_escape "$system_msg")\"}," fi request+="{\"role\":\"user\",\"content\":\"$(json_escape "$line")\"}" request+="],\"temperature\":temperature}}" echo "$request" count=$((count + 1)) done < "$file" > "$out_target" log "Generated $count batch requests" } # --------------------------------------------------------------------------- # cmd_convert - Format conversion (JSONL <-> CSV) # --------------------------------------------------------------------------- cmd_convert() { local input="" to="" output="" while [[ $# -gt 0 ]]; do case "$1" in --input) shift; input="$1" ;; --to) shift; to="$1" ;; --output) shift; output="$1" ;; *) die "Unknown option for convert: $1" ;; esac shift done [[ -n "$input" ]] || die "convert requires --input" [[ -f "$input" ]] || die "File not found: $input" [[ -n "$to" ]] || die "convert requires --to (jsonl or csv)" local out_target="-/dev/stdout" case "$to" in jsonl) # CSV to JSONL local first=true local headers=() while IFS=, read -r -a fields; do if [[ "$first" == true ]]; then first=false headers=("fields[@]") continue fi local json="{" local f_first=true for i in "!headers[@]"; do [[ "$f_first" == true ]] && f_first=false || json+="," local val="-" # Remove surrounding quotes if present val="val#\"" val="val%\"" json+="\"headers[$i]\":\"$(json_escape "$val")\"" done json+="}" echo "$json" done < "$input" > "$out_target" log "Converted CSV to JSONL" ;; csv) # JSONL to CSV - extract keys from first line as headers local first_line first_line=$(head -1 "$input") # Extract keys (simple approach: find "key": patterns) local keys=() while IFS= read -r key; do keys+=("$key") done < <(echo "$first_line" | grep -oP '"([^"]+)"\s*:' | grep -oP '"[^"]+"' | tr -d '"') # Print header local header="" local h_first=true for k in "keys[@]"; do [[ "$h_first" == true ]] && h_first=false || header+="," header+="$k" done echo "$header" > "$out_target" # Print rows while IFS= read -r line; do [[ -z "$line" ]] && continue local row="" local r_first=true for k in "keys[@]"; do [[ "$r_first" == true ]] && r_first=false || row+="," # Extract value for this key local val val=$(echo "$line" | grep -oP "\"k\"\s*:\s*\"[^\"]*\"" | head -1 | sed 's/.*: *"//;s/"$//' || echo "") if [[ -z "$val" ]]; then # Try numeric value val=$(echo "$line" | grep -oP "\"k\"\s*:\s*[0-9.]+" | head -1 | sed 's/.*: *//' || echo "") fi row+="\"$val\"" done echo "$row" done < "$input" >> "$out_target" log "Converted JSONL to CSV" ;; *) die "Unknown format: $to (supported: jsonl, csv)" ;; esac } # --------------------------------------------------------------------------- # Main dispatch # --------------------------------------------------------------------------- main() { [[ $# -ge 1 ]] || { cmd_help; exit 0; } local command="$1" shift case "$command" in chat) cmd_chat "$@" ;; embed) cmd_embed "$@" ;; finetune) cmd_finetune "$@" ;; cost) cmd_cost "$@" ;; batch) cmd_batch "$@" ;; convert) cmd_convert "$@" ;; help) cmd_help ;; *) die "Unknown command: $command. Run 'help' for usage." ;; esac } main "$@"
Manage sales leads locally. Use when adding prospects, scoring leads, setting follow-ups, tracking conversions, or viewing funnels.
--- name: leads description: "Manage sales leads locally. Use when adding prospects, scoring leads, setting follow-ups, tracking conversions, or viewing funnels." version: "3.4.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: - sales - crm - leads - pipeline - follow-up --- # Leads — Sales Lead CRM Manage sales leads through their lifecycle: add, score, follow up, convert, and report on your pipeline. ## Commands ### add — Add a new lead ```bash bash scripts/script.sh add "<name>" "<email>" "<company>" "[source]" ``` Creates a new lead with status `new`. Source defaults to `direct`. ### list — View leads ```bash bash scripts/script.sh list [status] [--sort score|date] ``` Lists all leads, optionally filtered by status (`new`, `contacted`, `qualified`, `converted`, `lost`). Sort by score or date. ### score — Score a lead ```bash bash scripts/script.sh score "<lead_id>" <points> "[reason]" ``` Assigns or adds score points to a lead. Score range: 0–100. Higher = more likely to convert. ### follow-up — Set follow-up reminder ```bash bash scripts/script.sh follow-up "<lead_id>" "<YYYY-MM-DD>" "<note>" ``` Schedules a follow-up action for a lead on the specified date with a note. ### convert — Mark lead as converted ```bash bash scripts/script.sh convert "<lead_id>" "[deal_value]" ``` Changes lead status to `converted` and optionally records deal value. ### pipeline — Sales funnel report ```bash bash scripts/script.sh pipeline [YYYY-MM] ``` Shows a funnel breakdown of leads by status with counts and conversion rates. Defaults to current month. ## Output All commands print plain text to stdout. Data is stored in `~/.leads/leads.json`. ## Requirements - bash 4+ - python3 (standard library only) ## Feedback Report issues or suggestions: [https://bytesagain.com/feedback/](https://bytesagain.com/feedback/) --- Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ###################################################################### # leads/scripts/script.sh — Sales Lead CRM # Powered by BytesAgain | bytesagain.com ###################################################################### DATA_DIR="HOME/.leads" LEADS_FILE="DATA_DIR/leads.json" # ── helpers ───────────────────────────────────────────────────────── ensure_data_dir() { mkdir -p "DATA_DIR" [[ -f "LEADS_FILE" ]] || echo '[]' > "LEADS_FILE" } today() { date +%Y-%m-%d } current_month() { date +%Y-%m } generate_id() { # Short unique ID based on timestamp + random printf "L%s%04d" "$(date +%s | tail -c 6)" "$((RANDOM % 10000))" } validate_date() { local d="-" if [[ -z "d" ]]; then echo "$(today)" return fi if [[ "d" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then echo "d" else echo "Error: invalid date format 'd'. Use YYYY-MM-DD." >&2 exit 1 fi } validate_number() { local val="-" label="-value" if [[ -z "val" ]] || ! [[ "val" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then echo "Error: label must be a positive number, got 'val'." >&2 exit 1 fi } validate_email() { local email="-" if [[ ! "email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then echo "Warning: 'email' may not be a valid email address." >&2 fi } # ── cmd_add ───────────────────────────────────────────────────────── cmd_add() { local name="-" email="-" company="-" source="-direct" if [[ -z "name" || -z "email" || -z "company" ]]; then echo "Usage: script.sh add \"<name>\" \"<email>\" \"<company>\" [source]" echo " source: direct | referral | website | social | event (default: direct)" exit 1 fi validate_email "email" ensure_data_dir local lead_id lead_id="$(generate_id)" local created created="$(today)" LEADS_FILE="$LEADS_FILE" python3 << 'PYEOF' "name" "email" "company" "source" "lead_id" "created" import json, sys, os leads_file = os.environ['LEADS_FILE'] with open(leads_file, 'r') as f: data = json.load(f) # Check for duplicate email for lead in data: if lead.get('email', '').lower() == sys.argv[2].lower(): print(f'⚠️ Lead with email {sys.argv[2]} already exists (ID: {lead["id"]})') sys.exit(1) lead = { 'id': sys.argv[5], 'name': sys.argv[1], 'email': sys.argv[2], 'company': sys.argv[3], 'source': sys.argv[4], 'status': 'new', 'score': 0, 'created': sys.argv[6], 'follow_ups': [], 'notes': [], 'deal_value': None } data.append(lead) with open(leads_file, 'w') as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f'✅ Lead added') print(f' ID: {lead["id"]}') print(f' Name: {lead["name"]}') print(f' Email: {lead["email"]}') print(f' Company: {lead["company"]}') print(f' Source: {lead["source"]}') print(f' Status: {lead["status"]}') PYEOF } # ── cmd_list ──────────────────────────────────────────────────────── cmd_list() { local filter_status="" sort_by="date" while [[ $# -gt 0 ]]; do case "$1" in --sort) sort_by="-date" shift 2 ;; new|contacted|qualified|converted|lost) filter_status="$1" shift ;; *) shift ;; esac done ensure_data_dir local today_str today_str="$(today)" LEADS_FILE="$LEADS_FILE" FILTER_STATUS="$filter_status" SORT_BY="$sort_by" TODAY_STR="$today_str" python3 << 'PYEOF' import json, os leads_file = os.environ['LEADS_FILE'] status_filter = os.environ['FILTER_STATUS'] sort_by = os.environ['SORT_BY'] today_str = os.environ['TODAY_STR'] with open(leads_file, 'r') as f: data = json.load(f) if status_filter: data = [l for l in data if l['status'] == status_filter] if sort_by == 'score': data.sort(key=lambda x: x.get('score', 0), reverse=True) else: data.sort(key=lambda x: x.get('created', ''), reverse=True) if not data: label = f' (status: {status_filter})' if status_filter else '' print(f'No leads found{label}.') raise SystemExit(0) status_icons = { 'new': '🆕', 'contacted': '📧', 'qualified': '⭐', 'converted': '🎉', 'lost': '❌' } title = f'Leads' + (f' [{status_filter}]' if status_filter else '') + f' (sorted by {sort_by})' print(f'📋 {title}') print('=' * 65) print(f'{"ID":<12s} {"Name":<18s} {"Company":<15s} {"Score":<6s} {"Status":<10s}') print('-' * 65) for l in data: icon = status_icons.get(l['status'], '❓') score_bar = '█' * (l.get('score', 0) // 10) + '░' * (10 - l.get('score', 0) // 10) print(f'{l["id"]:<12s} {l["name"]:<18s} {l["company"]:<15s} {l.get("score", 0):<6d} {icon} {l["status"]}') # Show upcoming follow-ups upcoming = [] for l in data: for fu in l.get('follow_ups', []): if fu.get('date', '') >= today_str and not fu.get('done', False): upcoming.append((fu['date'], l['name'], l['id'], fu.get('note', ''))) if upcoming: upcoming.sort() print() print('📅 Upcoming follow-ups:') for d, name, lid, note in upcoming[:5]: print(f' {d} — {name} ({lid}): {note}') print(f'\nTotal: {len(data)} leads') PYEOF } # ── cmd_score ─────────────────────────────────────────────────────── cmd_score() { local lead_id="-" points="-" reason="-manual scoring" if [[ -z "lead_id" || -z "points" ]]; then echo "Usage: script.sh score \"<lead_id>\" <points> [\"reason\"]" echo " points: 0-100" exit 1 fi validate_number "points" "points" ensure_data_dir LEADS_FILE="$LEADS_FILE" python3 << 'PYEOF' "lead_id" "points" "reason" import json, sys, os leads_file = os.environ['LEADS_FILE'] with open(leads_file, 'r') as f: data = json.load(f) lead_id = sys.argv[1] points = int(sys.argv[2]) reason = sys.argv[3] found = False for lead in data: if lead['id'] == lead_id: found = True old_score = lead.get('score', 0) new_score = min(100, max(0, old_score + points)) lead['score'] = new_score # Auto-upgrade status based on score if new_score >= 60 and lead['status'] == 'new': lead['status'] = 'contacted' if new_score >= 80 and lead['status'] in ('new', 'contacted'): lead['status'] = 'qualified' lead.setdefault('notes', []).append(f'Score: {old_score} → {new_score} ({reason})') with open(leads_file, 'w') as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f'📊 Score updated for {lead["name"]}') print(f' ID: {lead_id}') print(f' Score: {old_score} → {new_score}') print(f' Status: {lead["status"]}') print(f' Reason: {reason}') break if not found: print(f'Error: lead "{lead_id}" not found.', file=sys.stderr) sys.exit(1) PYEOF } # ── cmd_follow_up ─────────────────────────────────────────────────── cmd_follow_up() { local lead_id="-" fu_date="-" note="-" if [[ -z "lead_id" || -z "fu_date" || -z "note" ]]; then echo "Usage: script.sh follow-up \"<lead_id>\" \"<YYYY-MM-DD>\" \"<note>\"" exit 1 fi fu_date="$(validate_date "fu_date")" ensure_data_dir LEADS_FILE="$LEADS_FILE" python3 << 'PYEOF' "lead_id" "fu_date" "note" import json, sys, os leads_file = os.environ['LEADS_FILE'] with open(leads_file, 'r') as f: data = json.load(f) lead_id = sys.argv[1] fu_date = sys.argv[2] note = sys.argv[3] found = False for lead in data: if lead['id'] == lead_id: found = True fu = {'date': fu_date, 'note': note, 'done': False} lead.setdefault('follow_ups', []).append(fu) if lead['status'] == 'new': lead['status'] = 'contacted' with open(leads_file, 'w') as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f'📅 Follow-up scheduled') print(f' Lead: {lead["name"]} ({lead_id})') print(f' Date: {fu_date}') print(f' Note: {note}') print(f' Status: {lead["status"]}') total_fu = len(lead.get('follow_ups', [])) print(f' Total follow-ups: {total_fu}') break if not found: print(f'Error: lead "{lead_id}" not found.', file=sys.stderr) sys.exit(1) PYEOF } # ── cmd_convert ───────────────────────────────────────────────────── cmd_convert() { local lead_id="-" deal_value="-" if [[ -z "lead_id" ]]; then echo "Usage: script.sh convert \"<lead_id>\" [deal_value]" exit 1 fi if [[ -n "deal_value" ]]; then validate_number "deal_value" "deal_value" fi ensure_data_dir LEADS_FILE="$LEADS_FILE" python3 << 'PYEOF' "lead_id" "deal_value" import json, sys, os from datetime import date leads_file = os.environ['LEADS_FILE'] with open(leads_file, 'r') as f: data = json.load(f) lead_id = sys.argv[1] deal_value = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] else None found = False for lead in data: if lead['id'] == lead_id: found = True if lead['status'] == 'converted': print(f'⚠️ Lead {lead_id} is already converted.') sys.exit(0) old_status = lead['status'] lead['status'] = 'converted' lead['converted_date'] = str(date.today()) if deal_value: lead['deal_value'] = float(deal_value) lead.setdefault('notes', []).append(f'Converted from {old_status}') with open(leads_file, 'w') as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f'🎉 Lead converted!') print(f' Name: {lead["name"]}') print(f' Company: {lead["company"]}') print(f' From: {old_status} → converted') if deal_value: print(f' Deal: ,.2f') break if not found: print(f'Error: lead "{lead_id}" not found.', file=sys.stderr) sys.exit(1) PYEOF } # ── cmd_pipeline ──────────────────────────────────────────────────── cmd_pipeline() { local month="-" if [[ -z "month" ]]; then month="$(current_month)" fi ensure_data_dir LEADS_FILE="$LEADS_FILE" MONTH="$month" python3 << 'PYEOF' import json, os leads_file = os.environ['LEADS_FILE'] month = os.environ['MONTH'] with open(leads_file, 'r') as f: data = json.load(f) filtered = [l for l in data if l.get('created', '').startswith(month)] statuses = ['new', 'contacted', 'qualified', 'converted', 'lost'] status_icons = { 'new': '🆕', 'contacted': '📧', 'qualified': '⭐', 'converted': '🎉', 'lost': '❌' } counts = {} for s in statuses: counts[s] = len([l for l in filtered if l['status'] == s]) total = len(filtered) total_deal = sum(l.get('deal_value', 0) or 0 for l in filtered if l['status'] == 'converted') print(f'📊 Pipeline Report — {month}') print('=' * 50) if total == 0: print(' No leads found for this period.') raise SystemExit(0) # Funnel visualization max_bar = 30 for s in statuses: c = counts[s] pct = (c / total * 100) if total else 0 bar_len = int(pct / 100 * max_bar) bar = '█' * bar_len + '░' * (max_bar - bar_len) icon = status_icons.get(s, '❓') print(f' {icon} {s:<12s} {bar} {c:>3d} ({pct:.0f}%)') print() print(f' Total leads: {total}') converted = counts['converted'] if converted: conv_rate = converted / total * 100 print(f' Converted: {converted} ({conv_rate:.1f}%)') print(f' Total deal value: ,.2f') if converted > 0: avg_deal = total_deal / converted print(f' Avg deal value: ,.2f') lost = counts['lost'] if lost: loss_rate = lost / total * 100 print(f' Lost: {lost} ({loss_rate:.1f}%)') active = counts['new'] + counts['contacted'] + counts['qualified'] if active: print(f' Active pipeline: {active}') # Score distribution scores = [l.get('score', 0) for l in filtered] if scores: avg_score = sum(scores) / len(scores) print(f' Avg lead score: {avg_score:.0f}/100') # Source breakdown sources = {} for l in filtered: src = l.get('source', 'unknown') sources[src] = sources.get(src, 0) + 1 if sources: print() print(' Lead sources:') for src, cnt in sorted(sources.items(), key=lambda x: x[1], reverse=True): print(f' {src:<15s}: {cnt}') PYEOF } # ── cmd_help ──────────────────────────────────────────────────────── cmd_help() { cat <<'EOF' leads — Sales Lead CRM Commands: add "<name>" "<email>" "<company>" [source] Add a new lead list [status] [--sort score|date] View leads score "<lead_id>" <points> ["reason"] Score a lead (0-100) follow-up "<lead_id>" "<YYYY-MM-DD>" "<note>" Schedule follow-up convert "<lead_id>" [deal_value] Mark as converted pipeline [YYYY-MM] Sales funnel report help Show this help message Statuses: new → contacted → qualified → converted / lost Data stored in: ~/.leads/ EOF } # ── main dispatch ─────────────────────────────────────────────────── main() { local cmd="-help" shift || true case "cmd" in add) cmd_add "$@" ;; list) cmd_list "$@" ;; score) cmd_score "$@" ;; follow-up) cmd_follow_up "$@" ;; convert) cmd_convert "$@" ;; pipeline) cmd_pipeline "$@" ;; help|--help|-h) cmd_help ;; *) echo "Unknown command: cmd" >&2 cmd_help exit 1 ;; esac } main "$@"
Track orders locally. Use when creating orders, checking status, updating quantities, canceling, or generating sales reports.
--- name: orders description: "Track orders locally. Use when creating orders, checking status, updating quantities, canceling, or generating sales reports." version: "3.4.0" author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: - orders - management - ecommerce - tracking - inventory - report --- # Orders Skill Create, track, update, cancel, and report on orders. ## Commands ### create Create a new order. ```bash bash scripts/script.sh create <customer> <item> <quantity> <unit_price> [--note <text>] ``` ### list List all orders or filter by status. ```bash bash scripts/script.sh list [--status pending|shipped|delivered|cancelled] [--format table|json|csv] ``` ### status Query the status of a specific order. ```bash bash scripts/script.sh status <order_id> ``` ### update Update an existing order (status, quantity, or note). ```bash bash scripts/script.sh update <order_id> [--status <new_status>] [--quantity <num>] [--note <text>] ``` ### cancel Cancel an order by ID. ```bash bash scripts/script.sh cancel <order_id> [--reason <text>] ``` ### report Generate a summary report of all orders. ```bash bash scripts/script.sh report [--period today|week|month|all] [--format table|json] ``` ## Output All commands print to stdout. Order data is stored in `~/.orders/orders.json`. Order IDs are auto-generated. Use `--format json` for machine-readable output where supported. ## Requirements - bash 4+ - python3 (standard library only) ## Feedback Questions or suggestions? → [https://bytesagain.com/feedback/](https://bytesagain.com/feedback/) --- Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ############################################################################### # orders/scripts/script.sh — Order management system. # Create, list, query, update, cancel orders and generate reports. ############################################################################### DATA_DIR="HOME/.orders" ORDERS_FILE="DATA_DIR/orders.json" ensure_data_dir() { mkdir -p "DATA_DIR" if [[ ! -f "ORDERS_FILE" ]]; then echo '[]' > "ORDERS_FILE" fi } generate_order_id() { echo "ORD-$(date +%Y%m%d)-$(printf '%04d' $(( RANDOM % 10000 )))" } # ─── create ────────────────────────────────────────────────────────────────── cmd_create() { ensure_data_dir local customer="" item="" quantity="" unit_price="" note="" while [[ $# -gt 0 ]]; do case "$1" in --note) note="$2"; shift 2 ;; -*) echo "Unknown flag: $1" >&2; return 1 ;; *) if [[ -z "customer" ]]; then customer="$1" elif [[ -z "item" ]]; then item="$1" elif [[ -z "quantity" ]]; then quantity="$1" elif [[ -z "unit_price" ]]; then unit_price="$1" fi shift ;; esac done if [[ -z "customer" || -z "item" || -z "quantity" || -z "unit_price" ]]; then echo "Usage: script.sh create <customer> <item> <quantity> <unit_price> [--note text]" >&2 return 1 fi local order_id order_id=$(generate_order_id) local created_at created_at=$(date +%Y-%m-%dT%H:%M:%S) ORDERS_FILE="$ORDERS_FILE" ORDER_ID="$order_id" CUSTOMER="$customer" \ ITEM="$item" QUANTITY="$quantity" UNIT_PRICE="$unit_price" NOTE="$note" \ CREATED_AT="$created_at" python3 << 'PYEOF' import json, os orders_file = os.environ["ORDERS_FILE"] order_id = os.environ["ORDER_ID"] customer = os.environ["CUSTOMER"] item = os.environ["ITEM"] quantity = int(os.environ["QUANTITY"]) unit_price = float(os.environ["UNIT_PRICE"]) note = os.environ["NOTE"] created_at = os.environ["CREATED_AT"] orders = json.load(open(orders_file)) order = { 'id': order_id, 'customer': customer, 'item': item, 'quantity': quantity, 'unit_price': unit_price, 'total': quantity * unit_price, 'status': 'pending', 'note': note, 'created_at': created_at, 'updated_at': created_at } orders.append(order) json.dump(orders, open(orders_file, 'w'), indent=2) print(f'Order created: {order_id}') print(f' Customer: {customer}') print(f' Item: {item} x {quantity} @ unit_price') print(f' Total: .2f') print(f' Status: pending') PYEOF } # ─── list ──────────────────────────────────────────────────────────────────── cmd_list() { ensure_data_dir local status_filter="" format="table" while [[ $# -gt 0 ]]; do case "$1" in --status) status_filter="$2"; shift 2 ;; --format) format="$2"; shift 2 ;; -*) echo "Unknown flag: $1" >&2; return 1 ;; *) shift ;; esac done ORDERS_FILE="$ORDERS_FILE" STATUS_FILTER="$status_filter" FORMAT="$format" python3 << 'PYEOF' import json, os orders_file = os.environ["ORDERS_FILE"] status_filter = os.environ["STATUS_FILTER"] fmt = os.environ["FORMAT"] orders = json.load(open(orders_file)) if status_filter: orders = [o for o in orders if o['status'] == status_filter] if not orders: print('No orders found.') exit(0) if fmt == 'json': print(json.dumps(orders, indent=2)) elif fmt == 'csv': print('id,customer,item,quantity,unit_price,total,status,created_at') for o in orders: print(f"{o['id']},{o['customer']},{o['item']},{o['quantity']},{o['unit_price']},{o['total']},{o['status']},{o['created_at']}") else: print(f"{'ID':<20} {'Customer':<15} {'Item':<15} {'Qty':>5} {'Total':>10} {'Status':<12} {'Created':<20}") print('-' * 100) for o in orders: print(f"{o['id']:<20} {o['customer']:<15} {o['item']:<15} {o['quantity']:>5} {o['total']:>10.2f} {o['status']:<12} {o['created_at']:<20}") print(f'\nTotal orders: {len(orders)}') PYEOF } # ─── status ────────────────────────────────────────────────────────────────── cmd_status() { ensure_data_dir local order_id="" if [[ $# -ge 1 ]]; then order_id="$1" else echo "Usage: script.sh status <order_id>" >&2 return 1 fi ORDERS_FILE="$ORDERS_FILE" ORDER_ID="$order_id" python3 << 'PYEOF' import json, sys, os orders_file = os.environ["ORDERS_FILE"] oid = os.environ["ORDER_ID"] orders = json.load(open(orders_file)) found = None for o in orders: if o['id'] == oid: found = o break if not found: print(f'Order {oid} not found.') sys.exit(1) print(f'=== Order: {found["id"]} ===') print(f'Customer: {found["customer"]}') print(f'Item: {found["item"]}') print(f'Quantity: {found["quantity"]}') print(f'Unit Price: .2f') print(f'Total: .2f') print(f'Status: {found["status"]}') print(f'Note: {found.get("note", "")}') print(f'Created: {found["created_at"]}') print(f'Updated: {found["updated_at"]}') PYEOF } # ─── update ────────────────────────────────────────────────────────────────── cmd_update() { ensure_data_dir local order_id="" new_status="" new_quantity="" new_note="" while [[ $# -gt 0 ]]; do case "$1" in --status) new_status="$2"; shift 2 ;; --quantity) new_quantity="$2"; shift 2 ;; --note) new_note="$2"; shift 2 ;; -*) echo "Unknown flag: $1" >&2; return 1 ;; *) order_id="$1"; shift ;; esac done if [[ -z "order_id" ]]; then echo "Usage: script.sh update <order_id> [--status S] [--quantity N] [--note TEXT]" >&2 return 1 fi local updated_at updated_at=$(date +%Y-%m-%dT%H:%M:%S) ORDERS_FILE="$ORDERS_FILE" ORDER_ID="$order_id" NEW_STATUS="$new_status" \ NEW_QUANTITY="$new_quantity" NEW_NOTE="$new_note" UPDATED_AT="$updated_at" \ python3 << 'PYEOF' import json, sys, os orders_file = os.environ["ORDERS_FILE"] oid = os.environ["ORDER_ID"] new_status = os.environ["NEW_STATUS"] new_quantity = os.environ["NEW_QUANTITY"] new_note = os.environ["NEW_NOTE"] updated_at = os.environ["UPDATED_AT"] orders = json.load(open(orders_file)) found = False for o in orders: if o['id'] == oid: found = True changes = [] if new_status: o['status'] = new_status changes.append(f'status → {new_status}') if new_quantity: o['quantity'] = int(new_quantity) o['total'] = int(new_quantity) * o['unit_price'] changes.append(f'quantity → {new_quantity}') if new_note: o['note'] = new_note changes.append(f'note updated') o['updated_at'] = updated_at if changes: json.dump(orders, open(orders_file, 'w'), indent=2) print(f'Order {oid} updated: {", ".join(changes)}') else: print('No changes specified.') break if not found: print(f'Order {oid} not found.') sys.exit(1) PYEOF } # ─── cancel ────────────────────────────────────────────────────────────────── cmd_cancel() { ensure_data_dir local order_id="" reason="" while [[ $# -gt 0 ]]; do case "$1" in --reason) reason="$2"; shift 2 ;; -*) echo "Unknown flag: $1" >&2; return 1 ;; *) order_id="$1"; shift ;; esac done if [[ -z "order_id" ]]; then echo "Usage: script.sh cancel <order_id> [--reason TEXT]" >&2 return 1 fi local cancelled_at cancelled_at=$(date +%Y-%m-%dT%H:%M:%S) ORDERS_FILE="$ORDERS_FILE" ORDER_ID="$order_id" REASON="$reason" \ CANCELLED_AT="$cancelled_at" python3 << 'PYEOF' import json, sys, os orders_file = os.environ["ORDERS_FILE"] oid = os.environ["ORDER_ID"] reason = os.environ["REASON"] cancelled_at = os.environ["CANCELLED_AT"] orders = json.load(open(orders_file)) found = False for o in orders: if o['id'] == oid: found = True if o['status'] == 'cancelled': print(f'Order {oid} is already cancelled.') sys.exit(0) o['status'] = 'cancelled' o['updated_at'] = cancelled_at if reason: o['cancel_reason'] = reason json.dump(orders, open(orders_file, 'w'), indent=2) print(f'Order {oid} cancelled.') if reason: print(f'Reason: {reason}') break if not found: print(f'Order {oid} not found.') sys.exit(1) PYEOF } # ─── report ────────────────────────────────────────────────────────────────── cmd_report() { ensure_data_dir local period="all" format="table" while [[ $# -gt 0 ]]; do case "$1" in --period) period="$2"; shift 2 ;; --format) format="$2"; shift 2 ;; -*) echo "Unknown flag: $1" >&2; return 1 ;; *) shift ;; esac done ORDERS_FILE="$ORDERS_FILE" PERIOD="$period" FORMAT="$format" python3 << 'PYEOF' import json, os from datetime import datetime, timedelta orders_file = os.environ["ORDERS_FILE"] period = os.environ["PERIOD"] fmt = os.environ["FORMAT"] orders = json.load(open(orders_file)) # Filter by period now = datetime.now() period_map = { 'today': timedelta(days=1), 'week': timedelta(weeks=1), 'month': timedelta(days=30), } if period in period_map: cutoff = now - period_map[period] filtered = [] for o in orders: try: created = datetime.fromisoformat(o['created_at']) if created >= cutoff: filtered.append(o) except (ValueError, KeyError): filtered.append(o) else: filtered = orders if not filtered: print('No orders found for the specified period.') exit(0) # Compute stats total_orders = len(filtered) total_revenue = sum(o['total'] for o in filtered) by_status = {} for o in filtered: s = o['status'] by_status[s] = by_status.get(s, 0) + 1 top_items = {} for o in filtered: item = o['item'] top_items[item] = top_items.get(item, 0) + o['quantity'] top_customers = {} for o in filtered: c = o['customer'] top_customers[c] = top_customers.get(c, 0) + o['total'] if fmt == 'json': print(json.dumps({ 'period': period, 'total_orders': total_orders, 'total_revenue': round(total_revenue, 2), 'by_status': by_status, 'top_items': dict(sorted(top_items.items(), key=lambda x: -x[1])[:5]), 'top_customers': {k: round(v, 2) for k, v in sorted(top_customers.items(), key=lambda x: -x[1])[:5]} }, indent=2)) else: print(f'=== Order Report ({period}) ===') print(f'Total orders: {total_orders}') print(f'Total revenue: ,.2f') print() print('By Status:') for s, count in sorted(by_status.items()): pct = count / total_orders * 100 bar = '█' * int(pct / 2) print(f' {s:<15} {count:>5} ({pct:>5.1f}%) {bar}') print() print('Top Items (by quantity):') for item, qty in sorted(top_items.items(), key=lambda x: -x[1])[:5]: print(f' {item:<20} {qty:>8}') print() print('Top Customers (by spend):') for cust, spend in sorted(top_customers.items(), key=lambda x: -x[1])[:5]: print(f' {cust:<20} >10,.2f') PYEOF } # ─── help ──────────────────────────────────────────────────────────────────── cmd_help() { cat <<'EOF' orders — Order management system. Commands: create Create a new order (customer, item, quantity, price) list List all orders, optionally filter by status status Query the status of a specific order by ID update Update an order's status, quantity, or note cancel Cancel an order by ID report Generate a summary report with totals and breakdowns help Show this help message Examples: script.sh create "John Doe" Widget 5 19.99 --note "rush delivery" script.sh list --status pending --format table script.sh status ORD-20240115-0042 script.sh update ORD-20240115-0042 --status shipped script.sh cancel ORD-20240115-0042 --reason "customer request" script.sh report --period month --format json EOF } # ─── main dispatch ─────────────────────────────────────────────────────────── main() { if [[ $# -lt 1 ]]; then cmd_help exit 1 fi local command="$1" shift case "command" in create) cmd_create "$@" ;; list) cmd_list "$@" ;; status) cmd_status "$@" ;; update) cmd_update "$@" ;; cancel) cmd_cancel "$@" ;; report) cmd_report "$@" ;; help|--help|-h) cmd_help ;; *) echo "Unknown command: command" >&2 echo "Run 'script.sh help' for usage." >&2 exit 1 ;; esac } main "$@"
Search emojis by name or category and copy them for instant use. Use when finding emojis, browsing categories, copying codes.
--- name: EmojiList description: "Search emojis by name or category and copy them for instant use. Use when finding emojis, browsing categories, copying codes." version: "3.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["emoji","unicode","search","reference","symbols","text","chat","developer"] categories: ["Utility", "Productivity"] --- # EmojiList A built-in emoji reference and search tool with a database of 390+ emoji. Search by keyword, browse by category, get random emoji, or see the most popular ones — all from the terminal. No external dependencies required. ## Commands | Command | Description | |---------|-------------| | `emojilist search <keyword>` | Search emoji by name/keyword — matches against names and aliases (e.g. "fire", "heart", "cat") | | `emojilist category <name>` | List all emoji in a specific category with their names | | `emojilist random [count]` | Show random emoji (default: 5, max: 50) with names and categories | | `emojilist popular` | Top 25 most commonly used emoji worldwide, with usage context | | `emojilist list` | List all available categories with emoji count and sample preview | ## Categories | Category | Description | |----------|-------------| | `faces` | Smileys, expressions, emotions (~67 emoji) | | `gestures` | Hand signs, thumbs, pointing (~30 emoji) | | `hearts` | Hearts in all colors and styles (~17 emoji) | | `animals` | Animals, insects, sea creatures (~53 emoji) | | `food` | Food, drinks, fruits, meals (~70 emoji) | | `nature` | Plants, weather, celestial (~26 emoji) | | `tech` | Computers, devices, tools (~27 emoji) | | `travel` | Vehicles, buildings, places (~22 emoji) | | `sports` | Sports, games, trophies (~22 emoji) | | `symbols` | Signs, shapes, colors, marks (~41 emoji) | | `flags` | Country and specialty flags (~18 emoji) | ## Requirements - Bash 4+ (uses arrays) - Terminal with Unicode/emoji support ## Examples ```bash # Find fire-related emoji emojilist search fire # Browse all animal emoji emojilist category animals # Get 10 random emoji for inspiration emojilist random 10 # See what's most popular emojilist popular # See all categories at a glance emojilist list ``` FILE:scripts/script.sh #!/usr/bin/env bash # ============================================================================ # EmojiList — Emoji Reference & Search Tool # Powered by BytesAgain | bytesagain.com | [email protected] # ============================================================================ set -euo pipefail VERSION="3.0.0" SCRIPT_NAME="emojilist" # --- Colors ---------------------------------------------------------------- RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' CYAN='\033[0;36m' BOLD='\033[1m' NC='\033[0m' # --- Helpers --------------------------------------------------------------- info() { echo -e "BLUEℹNC $*"; } success() { echo -e "GREEN✔NC $*"; } warn() { echo -e "YELLOW⚠NC $*"; } error() { echo -e "RED✖NC $*" >&2; } die() { error "$@"; exit 1; } # --- Emoji Database ------------------------------------------------------- # Format: "emoji|name|category" EMOJI_DB=( # Faces - Smileys "😀|grinning face|faces" "😃|grinning face with big eyes|faces" "😄|grinning face with smiling eyes|faces" "😁|beaming face with smiling eyes|faces" "😆|grinning squinting face|faces" "😅|grinning face with sweat|faces" "🤣|rolling on the floor laughing|faces" "😂|face with tears of joy|faces" "🙂|slightly smiling face|faces" "🙃|upside down face|faces" "😉|winking face|faces" "😊|smiling face with smiling eyes|faces" "😇|smiling face with halo|faces" "🥰|smiling face with hearts|faces" "😍|smiling face with heart eyes|faces" "🤩|star struck|faces" "😘|face blowing a kiss|faces" "😗|kissing face|faces" "😚|kissing face with closed eyes|faces" "😙|kissing face with smiling eyes|faces" "🥲|smiling face with tear|faces" "😋|face savoring food|faces" "😛|face with tongue|faces" "😜|winking face with tongue|faces" "🤪|zany face|faces" "😝|squinting face with tongue|faces" "🤑|money mouth face|faces" "🤗|hugging face|faces" "🤭|face with hand over mouth|faces" "🤫|shushing face|faces" "🤔|thinking face|faces" "😐|neutral face|faces" "😑|expressionless face|faces" "😶|face without mouth|faces" "😏|smirking face|faces" "😒|unamused face|faces" "🙄|face with rolling eyes|faces" "😬|grimacing face|faces" "😮💨|face exhaling|faces" "🤥|lying face|faces" "😌|relieved face|faces" "😔|pensive face|faces" "😪|sleepy face|faces" "🤤|drooling face|faces" "😴|sleeping face|faces" "😷|face with medical mask|faces" "🤒|face with thermometer|faces" "🤕|face with head bandage|faces" "🤢|nauseated face|faces" "🤮|face vomiting|faces" "🥴|woozy face|faces" "😵|face with crossed out eyes|faces" "🤯|exploding head|faces" "😎|smiling face with sunglasses|faces" "🥸|disguised face|faces" "🤓|nerd face|faces" "😱|face screaming in fear|faces" "😨|fearful face|faces" "😰|anxious face with sweat|faces" "😥|sad but relieved face|faces" "😢|crying face|faces" "😭|loudly crying face|faces" "🥺|pleading face|faces" "😤|face with steam from nose|faces" "😡|pouting face|faces" "😠|angry face|faces" "🤬|face with symbols on mouth|faces" # Gestures / Hands "👋|waving hand|gestures" "🤚|raised back of hand|gestures" "🖐️|hand with fingers splayed|gestures" "✋|raised hand|gestures" "🖖|vulcan salute|gestures" "👌|ok hand|gestures" "🤌|pinched fingers|gestures" "🤏|pinching hand|gestures" "✌️|victory hand|gestures" "🤞|crossed fingers|gestures" "🤟|love you gesture|gestures" "🤘|sign of the horns|gestures" "🤙|call me hand|gestures" "👈|backhand index pointing left|gestures" "👉|backhand index pointing right|gestures" "👆|backhand index pointing up|gestures" "👇|backhand index pointing down|gestures" "☝️|index pointing up|gestures" "👍|thumbs up|gestures" "👎|thumbs down|gestures" "✊|raised fist|gestures" "👊|oncoming fist|gestures" "🤛|left facing fist|gestures" "🤜|right facing fist|gestures" "👏|clapping hands|gestures" "🙌|raising hands|gestures" "👐|open hands|gestures" "🤲|palms up together|gestures" "🙏|folded hands|gestures" "💪|flexed biceps|gestures" # Hearts & Love "❤️|red heart|hearts" "🧡|orange heart|hearts" "💛|yellow heart|hearts" "💚|green heart|hearts" "💙|blue heart|hearts" "💜|purple heart|hearts" "🖤|black heart|hearts" "🤍|white heart|hearts" "🤎|brown heart|hearts" "💔|broken heart|hearts" "💕|two hearts|hearts" "💞|revolving hearts|hearts" "💓|beating heart|hearts" "💗|growing heart|hearts" "💖|sparkling heart|hearts" "💘|heart with arrow|hearts" "💝|heart with ribbon|hearts" # Animals "🐶|dog face|animals" "🐱|cat face|animals" "🐭|mouse face|animals" "🐹|hamster|animals" "🐰|rabbit face|animals" "🦊|fox|animals" "🐻|bear|animals" "🐼|panda|animals" "🐨|koala|animals" "🐯|tiger face|animals" "🦁|lion|animals" "🐮|cow face|animals" "🐷|pig face|animals" "🐸|frog|animals" "🐵|monkey face|animals" "🙈|see no evil monkey|animals" "🙉|hear no evil monkey|animals" "🙊|speak no evil monkey|animals" "🐔|chicken|animals" "🐧|penguin|animals" "🐦|bird|animals" "🦅|eagle|animals" "🦆|duck|animals" "🦉|owl|animals" "🐺|wolf|animals" "🐗|boar|animals" "🐴|horse face|animals" "🦄|unicorn|animals" "🐝|honeybee|animals" "🐛|bug|animals" "🦋|butterfly|animals" "🐌|snail|animals" "🐙|octopus|animals" "🦑|squid|animals" "🦀|crab|animals" "🐠|tropical fish|animals" "🐟|fish|animals" "🐬|dolphin|animals" "🐳|spouting whale|animals" "🐋|whale|animals" "🦈|shark|animals" "🐊|crocodile|animals" "🐘|elephant|animals" "🦏|rhinoceros|animals" "🦒|giraffe|animals" "🐪|camel|animals" "🐫|two hump camel|animals" "🦙|llama|animals" "🐍|snake|animals" "🦎|lizard|animals" "🐢|turtle|animals" "🦖|t-rex dinosaur|animals" "🦕|sauropod dinosaur|animals" # Food & Drink "🍎|red apple|food" "🍐|pear|food" "🍊|tangerine orange|food" "🍋|lemon|food" "🍌|banana|food" "🍉|watermelon|food" "🍇|grapes|food" "🍓|strawberry|food" "🫐|blueberries|food" "🍈|melon|food" "🍒|cherries|food" "🍑|peach|food" "🥭|mango|food" "🍍|pineapple|food" "🥝|kiwi fruit|food" "🍅|tomato|food" "🥑|avocado|food" "🥦|broccoli|food" "🥬|leafy green|food" "🥒|cucumber|food" "🌶️|hot pepper chili|food" "🫑|bell pepper|food" "🌽|corn|food" "🥕|carrot|food" "🧄|garlic|food" "🧅|onion|food" "🥔|potato|food" "🍠|sweet potato|food" "🍕|pizza|food" "🍔|hamburger burger|food" "🍟|french fries|food" "🌭|hot dog|food" "🥪|sandwich|food" "🌮|taco|food" "🌯|burrito|food" "🍣|sushi|food" "🍱|bento box|food" "🥟|dumpling|food" "🍜|steaming bowl noodles ramen|food" "🍝|spaghetti pasta|food" "🍛|curry rice|food" "🍲|pot of food stew|food" "🥗|green salad|food" "🍿|popcorn|food" "🧈|butter|food" "🥞|pancakes|food" "🧇|waffle|food" "🍞|bread|food" "🥐|croissant|food" "🥖|baguette bread|food" "🧁|cupcake|food" "🍰|shortcake cake|food" "🎂|birthday cake|food" "🍩|doughnut donut|food" "🍪|cookie|food" "🍫|chocolate bar|food" "🍬|candy|food" "🍭|lollipop|food" "🍮|custard pudding|food" "☕|hot beverage coffee|food" "🍵|teacup tea|food" "🥤|cup with straw|food" "🧃|beverage box juice|food" "🍺|beer mug|food" "🍻|clinking beer mugs cheers|food" "🥂|clinking glasses champagne|food" "🍷|wine glass|food" "🍸|cocktail glass martini|food" "🥃|tumbler glass whiskey|food" "🧋|bubble tea boba|food" # Nature & Weather "🌸|cherry blossom|nature" "🌹|rose|nature" "🌺|hibiscus|nature" "🌻|sunflower|nature" "🌷|tulip|nature" "🌱|seedling|nature" "🌲|evergreen tree|nature" "🌳|deciduous tree|nature" "🌴|palm tree|nature" "🍀|four leaf clover|nature" "🍁|maple leaf|nature" "🍂|fallen leaf|nature" "🍃|leaf fluttering in wind|nature" "🌍|globe earth|nature" "🌙|crescent moon|nature" "⭐|star|nature" "🌟|glowing star|nature" "✨|sparkles|nature" "⚡|lightning zap|nature" "🔥|fire flame hot|nature" "💧|droplet water|nature" "🌊|ocean wave|nature" "☀️|sun|nature" "🌈|rainbow|nature" "❄️|snowflake|nature" "🌪️|tornado|nature" # Objects & Tech "💻|laptop computer|tech" "🖥️|desktop computer|tech" "⌨️|keyboard|tech" "🖱️|computer mouse|tech" "📱|mobile phone|tech" "📞|telephone|tech" "📧|email|tech" "💾|floppy disk|tech" "💿|optical disk cd|tech" "🔌|electric plug|tech" "🔋|battery|tech" "💡|light bulb idea|tech" "🔧|wrench tool|tech" "🔨|hammer|tech" "⚙️|gear settings|tech" "🔒|locked|tech" "🔓|unlocked|tech" "🔑|key|tech" "🗝️|old key|tech" "📦|package box|tech" "🗑️|wastebasket trash|tech" "📋|clipboard|tech" "📝|memo note|tech" "📎|paperclip|tech" "📊|bar chart|tech" "📈|chart increasing|tech" "📉|chart decreasing|tech" # Travel & Places "🚗|automobile car|travel" "🚕|taxi|travel" "🚌|bus|travel" "🚎|trolleybus|travel" "🏎️|racing car|travel" "🚓|police car|travel" "🚑|ambulance|travel" "🚒|fire engine|travel" "✈️|airplane|travel" "🚀|rocket|travel" "🛸|flying saucer ufo|travel" "🚁|helicopter|travel" "🚂|locomotive train|travel" "🚢|ship boat|travel" "🏠|house|travel" "🏢|office building|travel" "🏥|hospital|travel" "🏫|school|travel" "🏰|castle|travel" "⛪|church|travel" "🗼|tokyo tower|travel" "🗽|statue of liberty|travel" # Activities & Sports "⚽|soccer ball football|sports" "🏀|basketball|sports" "🏈|american football|sports" "⚾|baseball|sports" "🎾|tennis|sports" "🏐|volleyball|sports" "🏓|table tennis ping pong|sports" "🏸|badminton|sports" "🥊|boxing glove|sports" "🏊|person swimming|sports" "🚴|person biking|sports" "🏃|person running|sports" "🧗|person climbing|sports" "🎯|bullseye target|sports" "🎮|video game controller|sports" "🎲|game die dice|sports" "♟️|chess pawn|sports" "🎳|bowling|sports" "🏆|trophy winner|sports" "🥇|gold medal first|sports" "🥈|silver medal second|sports" "🥉|bronze medal third|sports" # Symbols & Signs "✅|check mark button|symbols" "❌|cross mark|symbols" "❓|question mark|symbols" "❗|exclamation mark|symbols" "⚠️|warning|symbols" "🚫|prohibited|symbols" "♻️|recycling symbol|symbols" "✏️|pencil|symbols" "📌|pushpin|symbols" "🏷️|label tag|symbols" "🔴|red circle|symbols" "🟠|orange circle|symbols" "🟡|yellow circle|symbols" "🟢|green circle|symbols" "🔵|blue circle|symbols" "🟣|purple circle|symbols" "⚫|black circle|symbols" "⚪|white circle|symbols" "🟥|red square|symbols" "🟧|orange square|symbols" "🟨|yellow square|symbols" "🟩|green square|symbols" "🟦|blue square|symbols" "🟪|purple square|symbols" "⬛|black large square|symbols" "⬜|white large square|symbols" "▶️|play button|symbols" "⏸️|pause button|symbols" "⏹️|stop button|symbols" "🔀|shuffle|symbols" "🔁|repeat|symbols" "💯|hundred points|symbols" "➕|plus|symbols" "➖|minus|symbols" "➗|divide|symbols" "✖️|multiply|symbols" "♾️|infinity|symbols" "💲|dollar sign money|symbols" "©️|copyright|symbols" "®️|registered|symbols" "™️|trade mark|symbols" # Flags (popular) "🇺🇸|united states usa flag|flags" "🇬🇧|united kingdom uk flag|flags" "🇨🇳|china flag|flags" "🇯🇵|japan flag|flags" "🇰🇷|south korea flag|flags" "🇫🇷|france flag|flags" "🇩🇪|germany flag|flags" "🇪🇸|spain flag|flags" "🇮🇹|italy flag|flags" "🇧🇷|brazil flag|flags" "🇷🇺|russia flag|flags" "🇮🇳|india flag|flags" "🇦🇺|australia flag|flags" "🇨🇦|canada flag|flags" "🇲🇽|mexico flag|flags" "🏳️🌈|rainbow flag pride|flags" "🏴☠️|pirate flag|flags" "🏁|checkered flag racing|flags" ) # All categories CATEGORIES=("faces" "gestures" "hearts" "animals" "food" "nature" "tech" "travel" "sports" "symbols" "flags") # --- Usage ----------------------------------------------------------------- usage() { cat <<EOF BOLDEmojiList vVERSIONNC — Emoji Reference & Search Tool Powered by BytesAgain | bytesagain.com | [email protected] BOLDUsage:NC SCRIPT_NAME <command> [arguments] BOLDCommands:NC search <keyword> Search emoji by name/keyword category <name> List emoji in a category random [count] Show random emoji (default: 5) popular Show most commonly used emoji list List all categories BOLDOptions:NC -h, --help Show this help -v, --version Show version BOLDCategories:NC faces, gestures, hearts, animals, food, nature, tech, travel, sports, symbols, flags BOLDExamples:NC SCRIPT_NAME search heart SCRIPT_NAME search fire SCRIPT_NAME category animals SCRIPT_NAME random 10 SCRIPT_NAME popular SCRIPT_NAME list EOF } # --- Commands -------------------------------------------------------------- cmd_search() { [[ -z "-" ]] && die "Missing argument: <keyword>" local keyword keyword=$(echo "$1" | tr '[:upper:]' '[:lower:]') info "Searching for: CYANkeywordNC" echo "" local count=0 for entry in "EMOJI_DB[@]"; do IFS='|' read -r emoji name category <<< "$entry" local name_lower name_lower=$(echo "$name" | tr '[:upper:]' '[:lower:]') if [[ "$name_lower" == *"$keyword"* ]]; then printf " %s %-40s [%s]\n" "$emoji" "$name" "$category" count=$((count + 1)) fi done echo "" if [[ $count -eq 0 ]]; then warn "No emoji found matching 'keyword'" info "Try broader terms like: face, heart, animal, food, star, hand" return 1 else success "Found count emoji matching 'keyword'" fi } cmd_category() { [[ -z "-" ]] && die "Missing argument: <category> (use 'list' to see categories)" local cat cat=$(echo "$1" | tr '[:upper:]' '[:lower:]') # Check if category exists local found=0 for c in "CATEGORIES[@]"; do [[ "$c" == "$cat" ]] && found=1 && break done [[ $found -eq 0 ]] && die "Unknown category 'cat'. Use 'SCRIPT_NAME list' to see available categories." info "Category: CYANcatNC" echo "" local count=0 for entry in "EMOJI_DB[@]"; do IFS='|' read -r emoji name category <<< "$entry" if [[ "$category" == "$cat" ]]; then printf " %s %s\n" "$emoji" "$name" count=$((count + 1)) fi done echo "" success "Total: count emoji in 'cat'" } cmd_random() { local count="-5" # Validate count is a number [[ "$count" =~ ^[0-9]+$ ]] || die "Count must be a number" [[ "$count" -lt 1 ]] && count=1 [[ "$count" -gt 50 ]] && count=50 local db_size=#EMOJI_DB[@] info "Random count emoji (from db_size total):" echo "" # Generate random indices local selected=0 local used_indices=() while [[ $selected -lt $count ]] && [[ $selected -lt $db_size ]]; do local idx=$((RANDOM % db_size)) # Check if already used local already=0 for used in "used_indices[@]+"${used_indices[@]"}"; do [[ "$used" -eq "$idx" ]] && already=1 && break done [[ $already -eq 1 ]] && continue used_indices+=("$idx") IFS='|' read -r emoji name category <<< "EMOJI_DB[$idx]" printf " %s %-40s [%s]\n" "$emoji" "$name" "$category" selected=$((selected + 1)) done echo "" } cmd_popular() { info "Most commonly used emoji:" echo "" local popular_emoji=( "😂|face with tears of joy|Most used on social media" "❤️|red heart|Universal love symbol" "🤣|rolling on the floor laughing|Top reaction emoji" "👍|thumbs up|Quick approval" "😭|loudly crying face|Emotional reactions" "🙏|folded hands|Please/thank you/prayer" "😘|face blowing a kiss|Affection" "🥰|smiling face with hearts|Love and warmth" "😍|smiling face with heart eyes|Adoration" "😊|smiling face with smiling eyes|Friendly positivity" "🔥|fire|Trending/hot/awesome" "😁|beaming face with smiling eyes|Joyful" "💕|two hearts|Love" "🥺|pleading face|Puppy eyes / begging" "😅|grinning face with sweat|Nervous/relief" "🤗|hugging face|Warm embrace" "🤔|thinking face|Pondering/questioning" "😎|smiling face with sunglasses|Cool" "👏|clapping hands|Applause/well done" "✨|sparkles|Magic/excitement/new" "💯|hundred points|Perfect score" "🎉|party popper|Celebration" "💪|flexed biceps|Strength/power" "🤷|person shrugging|Who knows" "👀|eyes|Looking/attention" ) local rank=0 for entry in "popular_emoji[@]"; do rank=$((rank + 1)) IFS='|' read -r emoji name note <<< "$entry" printf " %2d. %s %-35s CYAN%sNC\n" "$rank" "$emoji" "$name" "$note" done echo "" success "Top rank most popular emoji worldwide" } cmd_list() { info "Available emoji categories:" echo "" for cat in "CATEGORIES[@]"; do local count=0 local sample="" local sample_count=0 for entry in "EMOJI_DB[@]"; do IFS='|' read -r emoji name category <<< "$entry" if [[ "$category" == "$cat" ]]; then count=$((count + 1)) if [[ $sample_count -lt 5 ]]; then sample+="$emoji " sample_count=$((sample_count + 1)) fi fi done printf " BOLD%-12sNC (%3d emoji) %s\n" "$cat" "$count" "$sample" done echo "" local total=#EMOJI_DB[@] success "Total: total emoji across #CATEGORIES[@] categories" echo "" info "Usage: SCRIPT_NAME category <name>" } # --- Main ------------------------------------------------------------------ main() { [[ $# -eq 0 ]] && { usage; exit 0; } case "1" in -h|--help) usage ;; -v|--version) echo "SCRIPT_NAME vVERSION" ;; search) shift; cmd_search "-" ;; category) shift; cmd_category "-" ;; random) shift; cmd_random "-" ;; popular) cmd_popular ;; list) cmd_list ;; *) die "Unknown command: $1 (try --help)" ;; esac } main "$@"
System health checker and diagnostics tool. Quick overview of CPU usage, memory, disk space, uptime, load average, and running processes. Monitor system reso...
--- name: SysCheck description: "System health checker and diagnostics tool. Quick overview of CPU usage, memory, disk space, uptime, load average, and running processes. Monitor system resources, check service status, and get instant system health reports. Essential sysadmin toolkit." version: "2.0.0" author: "BytesAgain" tags: ["system","monitor","health","cpu","memory","disk","admin","devops","linux"] categories: ["System Tools", "Developer Tools", "Utility"] --- # SysCheck Quick system health at a glance. Know your machine's status in one command. ## Commands - `overview` — Full system health summary - `cpu` — CPU usage and load average - `memory` — Memory and swap usage - `disk` — Disk space usage - `processes` — Top processes by CPU/memory - `uptime` — System uptime info ## Usage Examples ```bash syscheck overview syscheck cpu syscheck disk ``` --- Powered by BytesAgain | bytesagain.com ## When to Use - when you need quick syscheck from the command line - to automate syscheck tasks in your workflow ## Output Returns logs to stdout. Redirect to a file with `syscheck run > output.txt`. --- *Powered by BytesAgain | bytesagain.com* *Feedback & Feature Requests: https://bytesagain.com/feedback* FILE:scripts/script.sh #!/usr/bin/env bash # Syscheck — sysops tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/syscheck" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "syscheck v2.0.0"; } _help() { echo "Syscheck v2.0.0 — sysops toolkit" echo "" echo "Usage: syscheck <command> [args]" echo "" echo "Commands:" echo " scan Scan" echo " monitor Monitor" echo " report Report" echo " alert Alert" echo " top Top" echo " usage Usage" echo " check Check" echo " fix Fix" echo " cleanup Cleanup" echo " backup Backup" echo " restore Restore" echo " log Log" echo " benchmark Benchmark" echo " compare Compare" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Syscheck Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Syscheck Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Syscheck Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: syscheck search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in scan) shift if [ $# -eq 0 ]; then echo "Recent scan entries:" tail -20 "$DATA_DIR/scan.log" 2>/dev/null || echo " No entries yet. Use: syscheck scan <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/scan.log" local total=$(wc -l < "$DATA_DIR/scan.log") echo " [Syscheck] scan: $input" echo " Saved. Total scan entries: $total" _log "scan" "$input" fi ;; monitor) shift if [ $# -eq 0 ]; then echo "Recent monitor entries:" tail -20 "$DATA_DIR/monitor.log" 2>/dev/null || echo " No entries yet. Use: syscheck monitor <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/monitor.log" local total=$(wc -l < "$DATA_DIR/monitor.log") echo " [Syscheck] monitor: $input" echo " Saved. Total monitor entries: $total" _log "monitor" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: syscheck report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Syscheck] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; alert) shift if [ $# -eq 0 ]; then echo "Recent alert entries:" tail -20 "$DATA_DIR/alert.log" 2>/dev/null || echo " No entries yet. Use: syscheck alert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/alert.log" local total=$(wc -l < "$DATA_DIR/alert.log") echo " [Syscheck] alert: $input" echo " Saved. Total alert entries: $total" _log "alert" "$input" fi ;; top) shift if [ $# -eq 0 ]; then echo "Recent top entries:" tail -20 "$DATA_DIR/top.log" 2>/dev/null || echo " No entries yet. Use: syscheck top <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/top.log" local total=$(wc -l < "$DATA_DIR/top.log") echo " [Syscheck] top: $input" echo " Saved. Total top entries: $total" _log "top" "$input" fi ;; usage) shift if [ $# -eq 0 ]; then echo "Recent usage entries:" tail -20 "$DATA_DIR/usage.log" 2>/dev/null || echo " No entries yet. Use: syscheck usage <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/usage.log" local total=$(wc -l < "$DATA_DIR/usage.log") echo " [Syscheck] usage: $input" echo " Saved. Total usage entries: $total" _log "usage" "$input" fi ;; check) shift if [ $# -eq 0 ]; then echo "Recent check entries:" tail -20 "$DATA_DIR/check.log" 2>/dev/null || echo " No entries yet. Use: syscheck check <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/check.log" local total=$(wc -l < "$DATA_DIR/check.log") echo " [Syscheck] check: $input" echo " Saved. Total check entries: $total" _log "check" "$input" fi ;; fix) shift if [ $# -eq 0 ]; then echo "Recent fix entries:" tail -20 "$DATA_DIR/fix.log" 2>/dev/null || echo " No entries yet. Use: syscheck fix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/fix.log" local total=$(wc -l < "$DATA_DIR/fix.log") echo " [Syscheck] fix: $input" echo " Saved. Total fix entries: $total" _log "fix" "$input" fi ;; cleanup) shift if [ $# -eq 0 ]; then echo "Recent cleanup entries:" tail -20 "$DATA_DIR/cleanup.log" 2>/dev/null || echo " No entries yet. Use: syscheck cleanup <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/cleanup.log" local total=$(wc -l < "$DATA_DIR/cleanup.log") echo " [Syscheck] cleanup: $input" echo " Saved. Total cleanup entries: $total" _log "cleanup" "$input" fi ;; backup) shift if [ $# -eq 0 ]; then echo "Recent backup entries:" tail -20 "$DATA_DIR/backup.log" 2>/dev/null || echo " No entries yet. Use: syscheck backup <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/backup.log" local total=$(wc -l < "$DATA_DIR/backup.log") echo " [Syscheck] backup: $input" echo " Saved. Total backup entries: $total" _log "backup" "$input" fi ;; restore) shift if [ $# -eq 0 ]; then echo "Recent restore entries:" tail -20 "$DATA_DIR/restore.log" 2>/dev/null || echo " No entries yet. Use: syscheck restore <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/restore.log" local total=$(wc -l < "$DATA_DIR/restore.log") echo " [Syscheck] restore: $input" echo " Saved. Total restore entries: $total" _log "restore" "$input" fi ;; log) shift if [ $# -eq 0 ]; then echo "Recent log entries:" tail -20 "$DATA_DIR/log.log" 2>/dev/null || echo " No entries yet. Use: syscheck log <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/log.log" local total=$(wc -l < "$DATA_DIR/log.log") echo " [Syscheck] log: $input" echo " Saved. Total log entries: $total" _log "log" "$input" fi ;; benchmark) shift if [ $# -eq 0 ]; then echo "Recent benchmark entries:" tail -20 "$DATA_DIR/benchmark.log" 2>/dev/null || echo " No entries yet. Use: syscheck benchmark <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/benchmark.log" local total=$(wc -l < "$DATA_DIR/benchmark.log") echo " [Syscheck] benchmark: $input" echo " Saved. Total benchmark entries: $total" _log "benchmark" "$input" fi ;; compare) shift if [ $# -eq 0 ]; then echo "Recent compare entries:" tail -20 "$DATA_DIR/compare.log" 2>/dev/null || echo " No entries yet. Use: syscheck compare <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/compare.log" local total=$(wc -l < "$DATA_DIR/compare.log") echo " [Syscheck] compare: $input" echo " Saved. Total compare entries: $total" _log "compare" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'syscheck help' for available commands." exit 1 ;; esac
Test and debug regex patterns against sample text. Use when checking match groups, validating patterns, generating replacements, linting syntax.
---
name: RegexPal
description: "Test and debug regex patterns against sample text. Use when checking match groups, validating patterns, generating replacements, linting syntax."
version: "3.0.0"
author: "BytesAgain"
homepage: https://bytesagain.com
source: https://github.com/bytesagain/ai-skills
tags: ["regex","regular-expression","pattern","matcher","tester","developer","text"]
categories: ["Developer Tools", "Utility"]
---
# RegexPal
A real regex tester and toolkit for the terminal. Test patterns against text, find matches in files with highlighted output, perform replacements, extract capturing groups, and get human-readable explanations of regex syntax.
## Commands
| Command | Description |
|---------|-------------|
| `regexpal test <pattern> <text>` | Test if a regex matches text — reports full match, partial match, groups, and named groups |
| `regexpal match <pattern> <file>` | Find all matches in a file — highlights matches in red, shows line numbers and match count |
| `regexpal replace <pattern> <replacement> <file>` | Replace all matches in a file and output to stdout. Supports backreferences (`\1`, `\2`) |
| `regexpal extract <pattern> <file>` | Extract capturing groups from all matches in a file — shows each group value per match |
| `regexpal explain <pattern>` | Break down a regex pattern — lists character classes, groups, tokens, and quantifiers |
## Requirements
- `python3` (uses `re` stdlib module)
## Examples
```bash
# Test a pattern
regexpal test '^\d{3}-\d{4}$' '123-4567'
# Find emails in a file
regexpal match '\w+@[\w.-]+' contacts.txt
# Replace version numbers
regexpal replace 'v(\d+)\.(\d+)' 'v\1.$((\\2+1))' changelog.md
# Extract domain parts from emails
regexpal extract '(\w+)@(\w+\.\w+)' emails.txt
# Understand a complex pattern
regexpal explain '(?<=@)[\w.-]+'
```
FILE:scripts/script.sh
#!/usr/bin/env bash
# ============================================================================
# RegexPal — Regex Tester & Toolkit
# Powered by BytesAgain | bytesagain.com | [email protected]
# ============================================================================
set -euo pipefail
VERSION="3.0.0"
SCRIPT_NAME="regexpal"
# --- Colors ----------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
NC='\033[0m'
# --- Helpers ---------------------------------------------------------------
info() { echo -e "BLUEℹNC $*"; }
success() { echo -e "GREEN✔NC $*"; }
warn() { echo -e "YELLOW⚠NC $*"; }
error() { echo -e "RED✖NC $*" >&2; }
die() { error "$@"; exit 1; }
need_file() {
[[ -z "-" ]] && die "Missing required argument: <file>"
[[ -f "$1" ]] || die "File not found: $1"
}
need_python3() {
command -v python3 &>/dev/null || die "python3 is required but not found"
}
# --- Usage -----------------------------------------------------------------
usage() {
cat <<EOF
BOLDRegexPal vVERSIONNC — Regex Tester & Toolkit
Powered by BytesAgain | bytesagain.com | [email protected]
BOLDUsage:NC
SCRIPT_NAME <command> [arguments]
BOLDCommands:NC
test <pattern> <text> Test if pattern matches text
match <pattern> <file> Find all matches in a file
replace <pattern> <replacement> <file> Replace matches in file (stdout)
extract <pattern> <file> Extract capturing groups from file
explain <pattern> Explain regex pattern parts
BOLDOptions:NC
-h, --help Show this help
-v, --version Show version
BOLDExamples:NC
SCRIPT_NAME test '^\d{3}-\d{4}$' '123-4567'
SCRIPT_NAME match '[A-Z]\w+' source.py
SCRIPT_NAME replace 'foo(\d+)' 'bar\1' input.txt
SCRIPT_NAME extract '(\w+)@(\w+\.\w+)' emails.txt
SCRIPT_NAME explain '(?<=@)[\w.-]+'
EOF
}
# --- Commands --------------------------------------------------------------
cmd_test() {
[[ -z "-" ]] && die "Missing argument: <pattern>"
[[ -z "-" ]] && die "Missing argument: <text>"
local pattern="$1"
local text="$2"
need_python3
info "Testing pattern: CYANpatternNC"
info "Against text: CYANtextNC"
echo ""
python3 -c "
import re, sys
pattern = sys.argv[1]
text = sys.argv[2]
try:
compiled = re.compile(pattern)
except re.error as e:
print(f'✖ Invalid regex: {e}', file=sys.stderr)
sys.exit(1)
# Full match
fm = compiled.fullmatch(text)
# Search (partial)
sm = compiled.search(text)
# Find all
fa = compiled.findall(text)
if fm:
print('✔ FULL MATCH')
if fm.groups():
for i, g in enumerate(fm.groups(), 1):
print(f' Group {i}: \"{g}\"')
if fm.groupdict():
for name, val in fm.groupdict().items():
print(f' Named \"{name}\": \"{val}\"')
elif sm:
print(f'✔ PARTIAL MATCH at position {sm.start()}-{sm.end()}')
print(f' Matched: \"{sm.group()}\"')
if sm.groups():
for i, g in enumerate(sm.groups(), 1):
print(f' Group {i}: \"{g}\"')
if len(fa) > 1:
print(f' Total matches found: {len(fa)}')
else:
print('✖ NO MATCH')
sys.exit(1)
" "$pattern" "$text"
}
cmd_match() {
[[ -z "-" ]] && die "Missing argument: <pattern>"
[[ -z "-" ]] && die "Missing argument: <file>"
need_file "$2"
need_python3
local pattern="$1"
local file="$2"
info "Pattern: CYANpatternNC"
info "File: CYANfileNC"
echo ""
python3 -c "
import re, sys
pattern = sys.argv[1]
filepath = sys.argv[2]
try:
compiled = re.compile(pattern)
except re.error as e:
print(f'✖ Invalid regex: {e}', file=sys.stderr)
sys.exit(1)
total_matches = 0
matching_lines = 0
with open(filepath, 'r', errors='replace') as f:
for line_num, line in enumerate(f, 1):
line = line.rstrip('\n')
matches = list(compiled.finditer(line))
if matches:
matching_lines += 1
total_matches += len(matches)
# Highlight matches in the line
highlighted = line
offset = 0
parts = []
last_end = 0
for m in matches:
parts.append(line[last_end:m.start()])
parts.append(f'\033[1;31m{m.group()}\033[0m')
last_end = m.end()
parts.append(line[last_end:])
highlighted = ''.join(parts)
print(f' {line_num:5}: {highlighted}')
print(f'')
if total_matches > 0:
print(f'✔ {total_matches} match(es) on {matching_lines} line(s)')
else:
print(f'✖ No matches found')
sys.exit(1)
" "$pattern" "$file"
}
cmd_replace() {
[[ -z "-" ]] && die "Missing argument: <pattern>"
[[ -z "-" ]] && die "Missing argument: <replacement>"
[[ -z "-" ]] && die "Missing argument: <file>"
need_file "$3"
need_python3
local pattern="$1"
local replacement="$2"
local file="$3"
info "Pattern: CYANpatternNC"
info "Replacement: CYANreplacementNC"
info "File: CYANfileNC"
info "(Output to stdout — pipe to file to save)"
echo "---"
python3 -c "
import re, sys
pattern = sys.argv[1]
replacement = sys.argv[2]
filepath = sys.argv[3]
try:
compiled = re.compile(pattern)
except re.error as e:
print(f'✖ Invalid regex: {e}', file=sys.stderr)
sys.exit(1)
total_replacements = 0
with open(filepath, 'r', errors='replace') as f:
for line in f:
new_line, count = compiled.subn(replacement, line)
total_replacements += count
sys.stdout.write(new_line)
print(f'---', file=sys.stderr)
print(f'✔ {total_replacements} replacement(s) made', file=sys.stderr)
" "$pattern" "$replacement" "$file"
}
cmd_extract() {
[[ -z "-" ]] && die "Missing argument: <pattern>"
[[ -z "-" ]] && die "Missing argument: <file>"
need_file "$2"
need_python3
local pattern="$1"
local file="$2"
info "Extracting groups for: CYANpatternNC"
info "From: CYANfileNC"
echo ""
python3 -c "
import re, sys
pattern = sys.argv[1]
filepath = sys.argv[2]
try:
compiled = re.compile(pattern)
except re.error as e:
print(f'✖ Invalid regex: {e}', file=sys.stderr)
sys.exit(1)
num_groups = compiled.groups
if num_groups == 0:
print('⚠ Pattern has no capturing groups — showing full matches instead', file=sys.stderr)
total = 0
with open(filepath, 'r', errors='replace') as f:
for line_num, line in enumerate(f, 1):
line = line.rstrip('\n')
for m in compiled.finditer(line):
total += 1
if num_groups == 0:
print(f' Line {line_num}: \"{m.group()}\"')
else:
groups = ', '.join(f'G{i}=\"{g}\"' for i, g in enumerate(m.groups(), 1) if g is not None)
print(f' Line {line_num}: {groups}')
print(f'')
print(f'✔ {total} match(es) extracted')
if total == 0:
sys.exit(1)
" "$pattern" "$file"
}
cmd_explain() {
[[ -z "-" ]] && die "Missing argument: <pattern>"
need_python3
local pattern="$1"
info "Explaining: CYANpatternNC"
echo ""
python3 -c "
import re, sys
pattern = sys.argv[1]
# Validate first
try:
compiled = re.compile(pattern)
except re.error as e:
print(f'✖ Invalid regex: {e}', file=sys.stderr)
sys.exit(1)
# Token explanations
explanations = {
'.': 'Any character (except newline)',
'*': 'Zero or more of the preceding',
'+': 'One or more of the preceding',
'?': 'Zero or one of the preceding (optional)',
'^': 'Start of string/line',
'\$': 'End of string/line',
'|': 'Alternation (OR)',
'\\\\d': 'Any digit [0-9]',
'\\\\D': 'Any non-digit',
'\\\\w': 'Any word character [a-zA-Z0-9_]',
'\\\\W': 'Any non-word character',
'\\\\s': 'Any whitespace',
'\\\\S': 'Any non-whitespace',
'\\\\b': 'Word boundary',
'\\\\B': 'Non-word boundary',
'\\\\n': 'Newline',
'\\\\t': 'Tab',
'\\\\\\\\': 'Literal backslash',
}
quantifiers = {
'{n}': 'Exactly n times',
'{n,}': 'At least n times',
'{n,m}': 'Between n and m times',
'*?': 'Zero or more (lazy/non-greedy)',
'+?': 'One or more (lazy/non-greedy)',
'??': 'Zero or one (lazy/non-greedy)',
}
groups_info = {
'(...)': 'Capturing group',
'(?:...)': 'Non-capturing group',
'(?P<name>...)': 'Named capturing group',
'(?=...)': 'Positive lookahead',
'(?!...)': 'Negative lookahead',
'(?<=...)': 'Positive lookbehind',
'(?<!...)': 'Negative lookbehind',
}
print('Pattern breakdown:')
print(f' {pattern}')
print()
# Walk through the pattern and explain parts
import re as re_mod
# Find character classes
classes = list(re_mod.finditer(r'\[([^\]]*)\]', pattern))
if classes:
print('Character classes:')
for m in classes:
print(f' [{m.group(1)}] — Match any of: {m.group(1)}')
print()
# Find groups
grps = list(re_mod.finditer(r'\((?:\?[P<:!=](?:<\w+>)?)?', pattern))
if grps:
print(f'Groups: {compiled.groups} capturing group(s)')
named = compiled.groupindex
if named:
for name, idx in named.items():
print(f' Group {idx} (named \"{name}\")')
print()
# Find used tokens
print('Tokens found:')
found_any = False
for token, desc in explanations.items():
if token in pattern or token.replace('\\\\\\\\', '\\\\') in pattern:
# More careful check
check = token.replace('\\\\\\\\', '\\\\')
if check in pattern:
print(f' {check:8s} → {desc}')
found_any = True
if not found_any:
print(' (only literal characters)')
print()
# Quantifier info
found_q = False
for token, desc in quantifiers.items():
if token.replace('{n}', '').replace('{n,}', '').replace('{n,m}', '') in pattern:
pass
import re as r2
quant_matches = list(r2.finditer(r'\{(\d+)(?:,(\d*))?\}', pattern))
if quant_matches:
print('Quantifiers:')
for m in quant_matches:
if m.group(2) is None:
print(f' {m.group()} → Exactly {m.group(1)} times')
elif m.group(2) == '':
print(f' {m.group()} → At least {m.group(1)} times')
else:
print(f' {m.group()} → Between {m.group(1)} and {m.group(2)} times')
print()
print(f'Flags: pattern compiles OK with {compiled.flags} flags')
print(f'Groups: {compiled.groups} capturing, {len(compiled.groupindex)} named')
" "$pattern"
}
# --- Main ------------------------------------------------------------------
main() {
[[ $# -eq 0 ]] && { usage; exit 0; }
case "1" in
-h|--help) usage ;;
-v|--version) echo "SCRIPT_NAME vVERSION" ;;
test) shift; cmd_test "-" "-" ;;
match) shift; cmd_match "-" "-" ;;
replace) shift; cmd_replace "-" "-" "-" ;;
extract) shift; cmd_extract "-" "-" ;;
explain) shift; cmd_explain "-" ;;
*) die "Unknown command: $1 (try --help)" ;;
esac
}
main "$@"
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Dnscheck concepts, best practices, and implementation patterns.
--- name: "dnscheck" version: "2.0.4" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Dnscheck concepts, best practices, and implementation patterns." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [dnscheck, reference] category: "devtools" --- # Dnscheck Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Dnscheck concepts, best practices, and implementation patterns. No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # dnscheck — Dnscheck reference tool. Use when working with dnscheck in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.3" show_help() { cat << 'HELPEOF' dnscheck v$VERSION — Dnscheck Reference Tool Usage: dnscheck <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Dnscheck — Overview ## What is Dnscheck? Dnscheck (dnscheck) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with dnscheck. ## Key Concepts - Core dnscheck principles and fundamentals - How dnscheck fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Dnscheck Matters Understanding dnscheck is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic dnscheck concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Dnscheck — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the dnscheck package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Dnscheck — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for dnscheck 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Dnscheck — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Dnscheck — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Dnscheck — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Dnscheck — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Dnscheck — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "dnscheck v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: dnscheck help"; exit 1 ;; esac
Manage cron jobs with execution logging and failure alert tracking. Use when adding tasks, monitoring execution, debugging failed crons.
--- name: CronJob description: "Manage cron jobs with execution logging and failure alert tracking. Use when adding tasks, monitoring execution, debugging failed crons." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["cron","job","scheduler","automation","admin","linux"] categories: ["Developer Tools", "Utility"] --- # CronJob A comprehensive sysops toolkit for scanning, monitoring, reporting, and maintaining scheduled job operations. CronJob provides 18+ commands for tracking job events, performing health checks, managing backups, benchmarking performance, and exporting operational data in multiple formats. ## Commands | Command | Description | |---------|-------------| | `cronjob scan <input>` | Record a scan entry — run without args to view recent scan entries | | `cronjob monitor <input>` | Record a monitoring observation — run without args to view recent entries | | `cronjob report <input>` | Log a report entry — run without args to view recent reports | | `cronjob alert <input>` | Record an alert — run without args to view recent alerts | | `cronjob top <input>` | Log a top-level event — run without args to view recent entries | | `cronjob usage <input>` | Track usage data — run without args to view recent usage entries | | `cronjob check <input>` | Record a check result — run without args to view recent checks | | `cronjob fix <input>` | Log a fix action — run without args to view recent fixes | | `cronjob cleanup <input>` | Record a cleanup operation — run without args to view recent cleanups | | `cronjob backup <input>` | Log a backup event — run without args to view recent backups | | `cronjob restore <input>` | Record a restore operation — run without args to view recent restores | | `cronjob log <input>` | Add a general log entry — run without args to view recent log entries | | `cronjob benchmark <input>` | Record a benchmark result — run without args to view recent benchmarks | | `cronjob compare <input>` | Log a comparison — run without args to view recent comparisons | | `cronjob stats` | Display summary statistics across all log categories | | `cronjob export <fmt>` | Export all data to a file (formats: `json`, `csv`, `txt`) | | `cronjob search <term>` | Search across all log files for a keyword | | `cronjob recent` | Show the 20 most recent activity entries from the history log | | `cronjob status` | Health check — shows version, data directory, entry count, disk usage | | `cronjob help` | Display available commands and usage information | | `cronjob version` | Print current version (v2.0.0) | Each data command (scan, monitor, report, etc.) works in two modes: - **With arguments**: Records the input with a timestamp into its dedicated log file - **Without arguments**: Displays the 20 most recent entries from that category ## Data Storage All data is stored locally in plain-text log files: - **Location**: `~/.local/share/cronjob/` - **Format**: Each entry is saved as `YYYY-MM-DD HH:MM|<value>` in per-category `.log` files - **History**: All operations are additionally logged to `history.log` with timestamps - **Export**: The `export` command can generate JSON, CSV, or TXT files from all log data - **No cloud sync** — everything stays on your machine ## Requirements - Bash 4.0+ (uses `set -euo pipefail`) - Standard Unix utilities: `date`, `wc`, `du`, `head`, `tail`, `grep`, `basename`, `cat` - No external dependencies, no API keys, no network access required - Works on Linux and macOS ## When to Use 1. **Cron job monitoring** — Track the execution status of scheduled jobs, log failures, and set up alerts for review 2. **Job audit trail** — Record scan, check, and report entries to maintain a complete history of job operations 3. **Backup & restore logging** — Log backup and restore events with timestamps so you always know what happened and when 4. **Performance benchmarking** — Record benchmark results for scheduled tasks and compare them over time to spot regressions 5. **Operational data export** — Export all collected logs in JSON, CSV, or TXT format for dashboards, compliance, or further analysis ## Examples ```bash # Record a scan of cron job health cronjob scan "all 12 scheduled jobs ran successfully today" # Log a monitoring observation cronjob monitor "backup-job took 45min, 3x longer than usual" # Record an alert for a failed job cronjob alert "daily-report cron failed at 03:00 — exit code 1" # Log a fix action taken cronjob fix "increased timeout for backup-job from 30m to 90m" # View summary statistics across all categories cronjob stats # Export all data to CSV for spreadsheet analysis cronjob export csv # Search for entries related to a specific job cronjob search "backup-job" # Quick health check cronjob status # View the 20 most recent activity entries cronjob recent ``` ## Configuration Set `CRONJOB_DIR` to change the data directory. Default: `~/.local/share/cronjob/` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # Cronjob — sysops tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/cronjob" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "cronjob v2.0.0"; } _help() { echo "Cronjob v2.0.0 — sysops toolkit" echo "" echo "Usage: cronjob <command> [args]" echo "" echo "Commands:" echo " scan Scan" echo " monitor Monitor" echo " report Report" echo " alert Alert" echo " top Top" echo " usage Usage" echo " check Check" echo " fix Fix" echo " cleanup Cleanup" echo " backup Backup" echo " restore Restore" echo " log Log" echo " benchmark Benchmark" echo " compare Compare" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Cronjob Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Cronjob Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Cronjob Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: cronjob search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in scan) shift if [ $# -eq 0 ]; then echo "Recent scan entries:" tail -20 "$DATA_DIR/scan.log" 2>/dev/null || echo " No entries yet. Use: cronjob scan <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/scan.log" local total=$(wc -l < "$DATA_DIR/scan.log") echo " [Cronjob] scan: $input" echo " Saved. Total scan entries: $total" _log "scan" "$input" fi ;; monitor) shift if [ $# -eq 0 ]; then echo "Recent monitor entries:" tail -20 "$DATA_DIR/monitor.log" 2>/dev/null || echo " No entries yet. Use: cronjob monitor <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/monitor.log" local total=$(wc -l < "$DATA_DIR/monitor.log") echo " [Cronjob] monitor: $input" echo " Saved. Total monitor entries: $total" _log "monitor" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: cronjob report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Cronjob] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; alert) shift if [ $# -eq 0 ]; then echo "Recent alert entries:" tail -20 "$DATA_DIR/alert.log" 2>/dev/null || echo " No entries yet. Use: cronjob alert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/alert.log" local total=$(wc -l < "$DATA_DIR/alert.log") echo " [Cronjob] alert: $input" echo " Saved. Total alert entries: $total" _log "alert" "$input" fi ;; top) shift if [ $# -eq 0 ]; then echo "Recent top entries:" tail -20 "$DATA_DIR/top.log" 2>/dev/null || echo " No entries yet. Use: cronjob top <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/top.log" local total=$(wc -l < "$DATA_DIR/top.log") echo " [Cronjob] top: $input" echo " Saved. Total top entries: $total" _log "top" "$input" fi ;; usage) shift if [ $# -eq 0 ]; then echo "Recent usage entries:" tail -20 "$DATA_DIR/usage.log" 2>/dev/null || echo " No entries yet. Use: cronjob usage <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/usage.log" local total=$(wc -l < "$DATA_DIR/usage.log") echo " [Cronjob] usage: $input" echo " Saved. Total usage entries: $total" _log "usage" "$input" fi ;; check) shift if [ $# -eq 0 ]; then echo "Recent check entries:" tail -20 "$DATA_DIR/check.log" 2>/dev/null || echo " No entries yet. Use: cronjob check <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/check.log" local total=$(wc -l < "$DATA_DIR/check.log") echo " [Cronjob] check: $input" echo " Saved. Total check entries: $total" _log "check" "$input" fi ;; fix) shift if [ $# -eq 0 ]; then echo "Recent fix entries:" tail -20 "$DATA_DIR/fix.log" 2>/dev/null || echo " No entries yet. Use: cronjob fix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/fix.log" local total=$(wc -l < "$DATA_DIR/fix.log") echo " [Cronjob] fix: $input" echo " Saved. Total fix entries: $total" _log "fix" "$input" fi ;; cleanup) shift if [ $# -eq 0 ]; then echo "Recent cleanup entries:" tail -20 "$DATA_DIR/cleanup.log" 2>/dev/null || echo " No entries yet. Use: cronjob cleanup <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/cleanup.log" local total=$(wc -l < "$DATA_DIR/cleanup.log") echo " [Cronjob] cleanup: $input" echo " Saved. Total cleanup entries: $total" _log "cleanup" "$input" fi ;; backup) shift if [ $# -eq 0 ]; then echo "Recent backup entries:" tail -20 "$DATA_DIR/backup.log" 2>/dev/null || echo " No entries yet. Use: cronjob backup <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/backup.log" local total=$(wc -l < "$DATA_DIR/backup.log") echo " [Cronjob] backup: $input" echo " Saved. Total backup entries: $total" _log "backup" "$input" fi ;; restore) shift if [ $# -eq 0 ]; then echo "Recent restore entries:" tail -20 "$DATA_DIR/restore.log" 2>/dev/null || echo " No entries yet. Use: cronjob restore <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/restore.log" local total=$(wc -l < "$DATA_DIR/restore.log") echo " [Cronjob] restore: $input" echo " Saved. Total restore entries: $total" _log "restore" "$input" fi ;; log) shift if [ $# -eq 0 ]; then echo "Recent log entries:" tail -20 "$DATA_DIR/log.log" 2>/dev/null || echo " No entries yet. Use: cronjob log <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/log.log" local total=$(wc -l < "$DATA_DIR/log.log") echo " [Cronjob] log: $input" echo " Saved. Total log entries: $total" _log "log" "$input" fi ;; benchmark) shift if [ $# -eq 0 ]; then echo "Recent benchmark entries:" tail -20 "$DATA_DIR/benchmark.log" 2>/dev/null || echo " No entries yet. Use: cronjob benchmark <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/benchmark.log" local total=$(wc -l < "$DATA_DIR/benchmark.log") echo " [Cronjob] benchmark: $input" echo " Saved. Total benchmark entries: $total" _log "benchmark" "$input" fi ;; compare) shift if [ $# -eq 0 ]; then echo "Recent compare entries:" tail -20 "$DATA_DIR/compare.log" 2>/dev/null || echo " No entries yet. Use: cronjob compare <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/compare.log" local total=$(wc -l < "$DATA_DIR/compare.log") echo " [Cronjob] compare: $input" echo " Saved. Total compare entries: $total" _log "compare" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'cronjob help' for available commands." exit 1 ;; esac
Convert units for length, weight, temperature, data, and speed. Use when switching measurement systems, sizing storage, or adjusting recipe quantities.
--- name: UnitConv description: "Convert units for length, weight, temperature, data, and speed. Use when switching measurement systems, sizing storage, or adjusting recipe quantities." version: "3.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["converter","units","metric","imperial","temperature","length","weight","utility"] categories: ["Utility", "Productivity"] --- # UnitConv — Unit Converter Convert between units for length, weight, temperature, speed, data storage, and time. Uses `awk` for precise math. ## Commands | Command | Description | |---------|-------------| | `length <value> <from> <to>` | Convert length: m, cm, mm, km, in, ft, yd, mi | | `weight <value> <from> <to>` | Convert weight: g, mg, kg, lb, oz, ton | | `temp <value> <from> <to>` | Convert temperature: C, F, K | | `speed <value> <from> <to>` | Convert speed: ms, kmh, mph, knots, fts | | `data <value> <from> <to>` | Convert data: B, KB, MB, GB, TB, PB | | `time <value> <from> <to>` | Convert time: s, m, h, d, w, mo, y | ## Examples ```bash # Length unitconv length 100 cm in # → 39.3701 in unitconv length 5 mi km # → 8.04672 km # Weight unitconv weight 150 lb kg # → 68.0389 kg # Temperature unitconv temp 100 C F # → 212°F unitconv temp 0 K C # → -273.15°C # Speed unitconv speed 60 mph kmh # → 96.5606 kmh unitconv speed 100 kmh knots # → 53.9957 knots # Data storage unitconv data 1024 MB GB # → 1 GB unitconv data 2 TB GB # → 2048 GB # Time unitconv time 3600 s h # → 1 h unitconv time 7 d h # → 168 h ``` ## Supported Units - **Length:** m (meter), cm, mm, km, in (inch), ft (foot), yd (yard), mi (mile) - **Weight:** g (gram), mg, kg, lb (pound), oz (ounce), ton - **Temperature:** C (Celsius), F (Fahrenheit), K (Kelvin) - **Speed:** ms (m/s), kmh (km/h), mph, knots, fts (ft/s) - **Data:** B (byte), KB, MB, GB, TB, PB - **Time:** s (second), m (minute), h (hour), d (day), w (week), mo (month ~30d), y (year ~365d) FILE:scripts/script.sh #!/usr/bin/env bash set -euo pipefail ############################################################################### # UnitConv — Unit Converter # Powered by BytesAgain | bytesagain.com | [email protected] ############################################################################### VERSION="3.0.0" SCRIPT_NAME="unitconv" # Colors RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m' CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m' err() { echo -e "RED[ERROR]NC $*" >&2; } info() { echo -e "CYAN[INFO]NC $*"; } usage() { cat <<EOF BOLDUnitConv vVERSIONNC — Unit Converter Powered by BytesAgain | bytesagain.com | [email protected] BOLDUsage:NC $SCRIPT_NAME length <value> <from> <to> Convert length (m, ft, in, cm, km, mi, yd, mm) $SCRIPT_NAME weight <value> <from> <to> Convert weight (kg, lb, oz, g, mg, ton) $SCRIPT_NAME temp <value> <from> <to> Convert temperature (C, F, K) $SCRIPT_NAME speed <value> <from> <to> Convert speed (kmh, mph, ms, knots, fts) $SCRIPT_NAME data <value> <from> <to> Convert data (B, KB, MB, GB, TB, PB) $SCRIPT_NAME time <value> <from> <to> Convert time (s, m, h, d, w, mo, y) BOLDExamples:NC $SCRIPT_NAME length 100 cm in # 100 centimeters to inches $SCRIPT_NAME weight 5 kg lb # 5 kilograms to pounds $SCRIPT_NAME temp 100 C F # 100 Celsius to Fahrenheit $SCRIPT_NAME speed 60 mph kmh # 60 mph to km/h $SCRIPT_NAME data 1024 MB GB # 1024 MB to GB $SCRIPT_NAME time 3600 s h # 3600 seconds to hours EOF } calc() { awk "BEGIN { printf \"%.6g\", $1 }" } convert_length() { local val="$1" from="$2" to="$3" # Everything to meters first local to_m from_m case "$from" in m) from_m="1" ;; cm) from_m="0.01" ;; mm) from_m="0.001" ;; km) from_m="1000" ;; in) from_m="0.0254" ;; ft) from_m="0.3048" ;; yd) from_m="0.9144" ;; mi) from_m="1609.344" ;; *) err "Unknown length unit: $from (use m/cm/mm/km/in/ft/yd/mi)"; exit 1 ;; esac case "$to" in m) to_m="1" ;; cm) to_m="0.01" ;; mm) to_m="0.001" ;; km) to_m="1000" ;; in) to_m="0.0254" ;; ft) to_m="0.3048" ;; yd) to_m="0.9144" ;; mi) to_m="1609.344" ;; *) err "Unknown length unit: $to (use m/cm/mm/km/in/ft/yd/mi)"; exit 1 ;; esac calc "val * from_m / to_m" } convert_weight() { local val="$1" from="$2" to="$3" local from_g to_g case "$from" in g) from_g="1" ;; mg) from_g="0.001" ;; kg) from_g="1000" ;; lb) from_g="453.592" ;; oz) from_g="28.3495" ;; ton) from_g="907185" ;; *) err "Unknown weight unit: $from (use g/mg/kg/lb/oz/ton)"; exit 1 ;; esac case "$to" in g) to_g="1" ;; mg) to_g="0.001" ;; kg) to_g="1000" ;; lb) to_g="453.592" ;; oz) to_g="28.3495" ;; ton) to_g="907185" ;; *) err "Unknown weight unit: $to (use g/mg/kg/lb/oz/ton)"; exit 1 ;; esac calc "val * from_g / to_g" } convert_temp() { local val="$1" from="$2" to="$3" # Normalize to uppercase from=$(echo "$from" | tr '[:lower:]' '[:upper:]') to=$(echo "$to" | tr '[:lower:]' '[:upper:]') if [[ "$from" == "$to" ]]; then calc "$val" return fi case "from-to" in C-F) calc "(val * 9/5) + 32" ;; C-K) calc "val + 273.15" ;; F-C) calc "(val - 32) * 5/9" ;; F-K) calc "((val - 32) * 5/9) + 273.15" ;; K-C) calc "val - 273.15" ;; K-F) calc "((val - 273.15) * 9/5) + 32" ;; *) err "Unknown temperature units: $from -> $to (use C/F/K)"; exit 1 ;; esac } convert_speed() { local val="$1" from="$2" to="$3" # Everything to m/s local from_ms to_ms case "$from" in ms|"m/s") from_ms="1" ;; kmh|"km/h") from_ms="0.277778" ;; mph) from_ms="0.44704" ;; knots|kn) from_ms="0.514444" ;; fts|"ft/s") from_ms="0.3048" ;; *) err "Unknown speed unit: $from (use ms/kmh/mph/knots/fts)"; exit 1 ;; esac case "$to" in ms|"m/s") to_ms="1" ;; kmh|"km/h") to_ms="0.277778" ;; mph) to_ms="0.44704" ;; knots|kn) to_ms="0.514444" ;; fts|"ft/s") to_ms="0.3048" ;; *) err "Unknown speed unit: $to (use ms/kmh/mph/knots/fts)"; exit 1 ;; esac calc "val * from_ms / to_ms" } convert_data() { local val="$1" from="$2" to="$3" # Uppercase from=$(echo "$from" | tr '[:lower:]' '[:upper:]') to=$(echo "$to" | tr '[:lower:]' '[:upper:]') # Everything to bytes local from_b to_b case "$from" in B) from_b="1" ;; KB) from_b="1024" ;; MB) from_b="1048576" ;; GB) from_b="1073741824" ;; TB) from_b="1099511627776" ;; PB) from_b="1125899906842624" ;; *) err "Unknown data unit: $from (use B/KB/MB/GB/TB/PB)"; exit 1 ;; esac case "$to" in B) to_b="1" ;; KB) to_b="1024" ;; MB) to_b="1048576" ;; GB) to_b="1073741824" ;; TB) to_b="1099511627776" ;; PB) to_b="1125899906842624" ;; *) err "Unknown data unit: $to (use B/KB/MB/GB/TB/PB)"; exit 1 ;; esac calc "val * from_b / to_b" } convert_time() { local val="$1" from="$2" to="$3" # Everything to seconds local from_s to_s case "$from" in s) from_s="1" ;; m|min) from_s="60" ;; h|hr) from_s="3600" ;; d|day) from_s="86400" ;; w|wk) from_s="604800" ;; mo) from_s="2592000" ;; y|yr) from_s="31536000" ;; *) err "Unknown time unit: $from (use s/m/h/d/w/mo/y)"; exit 1 ;; esac case "$to" in s) to_s="1" ;; m|min) to_s="60" ;; h|hr) to_s="3600" ;; d|day) to_s="86400" ;; w|wk) to_s="604800" ;; mo) to_s="2592000" ;; y|yr) to_s="31536000" ;; *) err "Unknown time unit: $to (use s/m/h/d/w/mo/y)"; exit 1 ;; esac calc "val * from_s / to_s" } # Main dispatch if [[ $# -lt 1 ]]; then usage exit 0 fi cmd="$1"; shift case "$cmd" in length) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME length <value> <from> <to>"; exit 1; } result=$(convert_length "$1" "$2" "$3") echo -e "GREEN1 2NC = BOLDresult 3NC" ;; weight) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME weight <value> <from> <to>"; exit 1; } result=$(convert_weight "$1" "$2" "$3") echo -e "GREEN1 2NC = BOLDresult 3NC" ;; temp) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME temp <value> <from> <to>"; exit 1; } result=$(convert_temp "$1" "$2" "$3") echo -e "GREEN1°2NC = BOLDresult°3NC" ;; speed) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME speed <value> <from> <to>"; exit 1; } result=$(convert_speed "$1" "$2" "$3") echo -e "GREEN1 2NC = BOLDresult 3NC" ;; data) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME data <value> <from> <to>"; exit 1; } result=$(convert_data "$1" "$2" "$3") echo -e "GREEN1 2NC = BOLDresult 3NC" ;; time) [[ $# -ge 3 ]] || { err "Usage: $SCRIPT_NAME time <value> <from> <to>"; exit 1; } result=$(convert_time "$1" "$2" "$3") echo -e "GREEN1 2NC = BOLDresult 3NC" ;; -h|--help) usage ;; *) err "Unknown command: $cmd" usage exit 1 ;; esac
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Fakerjs concepts, best practices, and implementation patterns.
--- name: "fakerjs" version: "3.0.1" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Fakerjs concepts, best practices, and implementation patterns." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [fakerjs, reference] category: "devtools" --- # Fakerjs Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Fakerjs concepts, best practices, and implementation patterns. No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # fakerjs — Fakerjs reference tool. Use when working with fakerjs in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="3.0.0" show_help() { cat << 'HELPEOF' fakerjs v$VERSION — Fakerjs Reference Tool Usage: fakerjs <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Fakerjs — Overview ## What is Fakerjs? Fakerjs (fakerjs) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with fakerjs. ## Key Concepts - Core fakerjs principles and fundamentals - How fakerjs fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Fakerjs Matters Understanding fakerjs is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic fakerjs concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Fakerjs — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the fakerjs package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Fakerjs — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for fakerjs 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Fakerjs — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Fakerjs — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Fakerjs — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Fakerjs — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Fakerjs — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "fakerjs v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: fakerjs help"; exit 1 ;; esac
Font pairing and typography helper for designers and developers. Use when you need fontpick.
--- name: FontPick description: "Font pairing and typography helper for designers and developers. Use when you need fontpick." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["font","typography","design","css","pairing","web","style","ui"] categories: ["Design", "Developer Tools", "Utility"] --- # FontPick Pick the right fonts. Every time. FontPick gives you selectd pairings and type scales. ## Why FontPick? - **selectd pairings**: Tested heading + body combinations - **Multiple styles**: Modern, classic, minimal, bold, and code fonts - **Font stacks**: Ready-to-use CSS font-family declarations - **Type scales**: Calculate harmonious size systems - **Typography tips**: Principles for better font choices ## Commands - `pair [style]` — Get font pairings (modern/classic/minimal/bold/code) - `stack [use]` — CSS font stacks (web/email/print) - `size [base_px]` — Generate type scale from base size (default: 16px) - `contrast` — Typography contrast and pairing principles - `info` — Version info - `help` — Show commands ## Usage Examples ```bash fontpick pair modern fontpick pair code fontpick stack web fontpick size 18 fontpick contrast ``` ## Style Guide | Style | Best For | |-------|----------| | Modern | SaaS, tech, startups | | Classic | Publishing, editorial | | Minimal | Portfolio, luxury brands | | Bold | Marketing, headlines | | Code | Developer tools, IDEs | --- 💬 Feedback & Feature Requests: https://bytesagain.com/feedback Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # Fontpick — design tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/fontpick" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "fontpick v2.0.0"; } _help() { echo "Fontpick v2.0.0 — design toolkit" echo "" echo "Usage: fontpick <command> [args]" echo "" echo "Commands:" echo " palette Palette" echo " preview Preview" echo " generate Generate" echo " convert Convert" echo " harmonize Harmonize" echo " contrast Contrast" echo " export Export" echo " random Random" echo " browse Browse" echo " mix Mix" echo " gradient Gradient" echo " swatch Swatch" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Fontpick Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Fontpick Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Fontpick Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: fontpick search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in palette) shift if [ $# -eq 0 ]; then echo "Recent palette entries:" tail -20 "$DATA_DIR/palette.log" 2>/dev/null || echo " No entries yet. Use: fontpick palette <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/palette.log" local total=$(wc -l < "$DATA_DIR/palette.log") echo " [Fontpick] palette: $input" echo " Saved. Total palette entries: $total" _log "palette" "$input" fi ;; preview) shift if [ $# -eq 0 ]; then echo "Recent preview entries:" tail -20 "$DATA_DIR/preview.log" 2>/dev/null || echo " No entries yet. Use: fontpick preview <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/preview.log" local total=$(wc -l < "$DATA_DIR/preview.log") echo " [Fontpick] preview: $input" echo " Saved. Total preview entries: $total" _log "preview" "$input" fi ;; generate) shift if [ $# -eq 0 ]; then echo "Recent generate entries:" tail -20 "$DATA_DIR/generate.log" 2>/dev/null || echo " No entries yet. Use: fontpick generate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/generate.log" local total=$(wc -l < "$DATA_DIR/generate.log") echo " [Fontpick] generate: $input" echo " Saved. Total generate entries: $total" _log "generate" "$input" fi ;; convert) shift if [ $# -eq 0 ]; then echo "Recent convert entries:" tail -20 "$DATA_DIR/convert.log" 2>/dev/null || echo " No entries yet. Use: fontpick convert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/convert.log" local total=$(wc -l < "$DATA_DIR/convert.log") echo " [Fontpick] convert: $input" echo " Saved. Total convert entries: $total" _log "convert" "$input" fi ;; harmonize) shift if [ $# -eq 0 ]; then echo "Recent harmonize entries:" tail -20 "$DATA_DIR/harmonize.log" 2>/dev/null || echo " No entries yet. Use: fontpick harmonize <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/harmonize.log" local total=$(wc -l < "$DATA_DIR/harmonize.log") echo " [Fontpick] harmonize: $input" echo " Saved. Total harmonize entries: $total" _log "harmonize" "$input" fi ;; contrast) shift if [ $# -eq 0 ]; then echo "Recent contrast entries:" tail -20 "$DATA_DIR/contrast.log" 2>/dev/null || echo " No entries yet. Use: fontpick contrast <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/contrast.log" local total=$(wc -l < "$DATA_DIR/contrast.log") echo " [Fontpick] contrast: $input" echo " Saved. Total contrast entries: $total" _log "contrast" "$input" fi ;; export) shift if [ $# -eq 0 ]; then echo "Recent export entries:" tail -20 "$DATA_DIR/export.log" 2>/dev/null || echo " No entries yet. Use: fontpick export <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/export.log" local total=$(wc -l < "$DATA_DIR/export.log") echo " [Fontpick] export: $input" echo " Saved. Total export entries: $total" _log "export" "$input" fi ;; random) shift if [ $# -eq 0 ]; then echo "Recent random entries:" tail -20 "$DATA_DIR/random.log" 2>/dev/null || echo " No entries yet. Use: fontpick random <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/random.log" local total=$(wc -l < "$DATA_DIR/random.log") echo " [Fontpick] random: $input" echo " Saved. Total random entries: $total" _log "random" "$input" fi ;; browse) shift if [ $# -eq 0 ]; then echo "Recent browse entries:" tail -20 "$DATA_DIR/browse.log" 2>/dev/null || echo " No entries yet. Use: fontpick browse <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/browse.log" local total=$(wc -l < "$DATA_DIR/browse.log") echo " [Fontpick] browse: $input" echo " Saved. Total browse entries: $total" _log "browse" "$input" fi ;; mix) shift if [ $# -eq 0 ]; then echo "Recent mix entries:" tail -20 "$DATA_DIR/mix.log" 2>/dev/null || echo " No entries yet. Use: fontpick mix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/mix.log" local total=$(wc -l < "$DATA_DIR/mix.log") echo " [Fontpick] mix: $input" echo " Saved. Total mix entries: $total" _log "mix" "$input" fi ;; gradient) shift if [ $# -eq 0 ]; then echo "Recent gradient entries:" tail -20 "$DATA_DIR/gradient.log" 2>/dev/null || echo " No entries yet. Use: fontpick gradient <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/gradient.log" local total=$(wc -l < "$DATA_DIR/gradient.log") echo " [Fontpick] gradient: $input" echo " Saved. Total gradient entries: $total" _log "gradient" "$input" fi ;; swatch) shift if [ $# -eq 0 ]; then echo "Recent swatch entries:" tail -20 "$DATA_DIR/swatch.log" 2>/dev/null || echo " No entries yet. Use: fontpick swatch <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/swatch.log" local total=$(wc -l < "$DATA_DIR/swatch.log") echo " [Fontpick] swatch: $input" echo " Saved. Total swatch entries: $total" _log "swatch" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'fontpick help' for available commands." exit 1 ;; esac
Analyze codebases quickly with AI-powered intelligence and insights. Use when understanding unfamiliar repos, checking quality, or generating summaries.
--- name: CodePal description: "Analyze codebases quickly with AI-powered intelligence and insights. Use when understanding unfamiliar repos, checking quality, or generating summaries." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["code","developer","analysis","todo","loc","dependencies","programming","devtools"] categories: ["Developer Tools", "Productivity"] --- # CodePal A full-featured devtools toolkit for checking, validating, generating, formatting, linting, explaining, converting, diffing, previewing, and fixing code — with built-in logging, search, statistics, and data export. ## Commands | Command | Description | |---------|-------------| | `check <input>` | Check code and log the result; without args shows recent check entries | | `validate <input>` | Validate code input; without args shows recent validate entries | | `generate <input>` | Generate code from a description; without args shows recent entries | | `format <input>` | Format code; without args shows recent format entries | | `lint <input>` | Lint code for potential issues; without args shows recent lint entries | | `explain <input>` | Explain a code snippet or concept; without args shows recent entries | | `convert <input>` | Convert code between languages or formats; without args shows recent entries | | `template <input>` | Create or apply code templates; without args shows recent entries | | `diff <input>` | Log code differences; without args shows recent diff entries | | `preview <input>` | Preview code output; without args shows recent preview entries | | `fix <input>` | Record a code fix; without args shows recent fix entries | | `report <input>` | Generate a code report; without args shows recent report entries | | `stats` | Show summary statistics across all log categories | | `export <fmt>` | Export all data (json, csv, or txt) | | `search <term>` | Search across all logged entries for a keyword | | `recent` | Show the 20 most recent entries from the activity log | | `status` | Health check — version, data dir, total entries, disk usage, last activity | | `help` | Show all available commands | | `version` | Print version (v2.0.0) | ## Usage ```bash codepal <command> [args] ``` Each command with arguments logs the input with a timestamp to a category-specific log file. Running a command with no arguments shows the most recent entries for that category. ## Data Storage - **Default location**: `~/.local/share/codepal` - **Log files**: Each command has its own log file (e.g., `check.log`, `lint.log`, `generate.log`) - **History**: All actions are also recorded in `history.log` with timestamps - **Export formats**: JSON (structured array of objects), CSV (type/time/value columns), plain text (grouped by category) ## Requirements - Bash 4+ (strict mode: `set -euo pipefail`) - No external dependencies or API keys required - Standard Unix tools (`date`, `wc`, `grep`, `du`, `head`, `tail`) ## When to Use 1. **Code review tracking** — Use `check`, `lint`, and `validate` to log issues discovered during code review sessions, then `search` to find them later 2. **Learning unfamiliar codebases** — Use `explain` to document your understanding of code patterns, then `report` to create summaries 3. **Code generation and templating** — Use `generate` to log code generation prompts and `template` to track template usage 4. **Diffing and debugging** — Use `diff` to record code changes and `fix` to document bug fixes, creating an audit trail 5. **Team metrics and reporting** — Use `stats` for activity summaries, `export json` to feed into dashboards, and `recent` for quick status checks ## Examples ```bash # Check a function codepal check "validateEmail() is missing null check" # Generate a code snippet description codepal generate "React hook for debounced search" # Lint a file codepal lint "server.js:42 — unused variable 'config'" # Explain a concept codepal explain "JavaScript closure in event handler" # Record a diff codepal diff "Refactored auth middleware to use async/await" # Fix a bug codepal fix "Off-by-one error in pagination logic" # View aggregate statistics codepal stats # Export all logged data as CSV codepal export csv # Search for entries about authentication codepal search "auth" # Show recent activity codepal recent # Health check codepal status ``` ## Output - Command results print to stdout - Entries are timestamped (`YYYY-MM-DD HH:MM`) and persisted to `~/.local/share/codepal/<category>.log` - Export files are written to `~/.local/share/codepal/export.<fmt>` with a byte count confirmation --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash # Codepal — devtools tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/codepal" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "codepal v2.0.0"; } _help() { echo "Codepal v2.0.0 — devtools toolkit" echo "" echo "Usage: codepal <command> [args]" echo "" echo "Commands:" echo " check Check" echo " validate Validate" echo " generate Generate" echo " format Format" echo " lint Lint" echo " explain Explain" echo " convert Convert" echo " template Template" echo " diff Diff" echo " preview Preview" echo " fix Fix" echo " report Report" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Codepal Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Since: $(head -1 "$DATA_DIR/history.log" 2>/dev/null | cut -d'|' -f1 || echo 'N/A')" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "" >> "$out" echo "]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out" done < "$f" done ;; txt) echo "=== Codepal Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" echo "" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Codepal Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" local last=$(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo "never") echo " Last activity: $last" echo " Status: OK" } _search() { local term="?Usage: codepal search <term>" echo "Searching for: $term" local found=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local matches=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$matches" ]; then echo " --- $(basename "$f" .log) ---" echo "$matches" | while read -r line; do echo " $line" found=$((found + 1)) done fi done [ $found -eq 0 ] && echo " No matches found." } _recent() { echo "=== Recent Activity ===" if [ -f "$DATA_DIR/history.log" ]; then tail -20 "$DATA_DIR/history.log" | while IFS='' read -r line; do echo " $line" done else echo " No activity yet." fi } # Main dispatch case "-help" in check) shift if [ $# -eq 0 ]; then echo "Recent check entries:" tail -20 "$DATA_DIR/check.log" 2>/dev/null || echo " No entries yet. Use: codepal check <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/check.log" local total=$(wc -l < "$DATA_DIR/check.log") echo " [Codepal] check: $input" echo " Saved. Total check entries: $total" _log "check" "$input" fi ;; validate) shift if [ $# -eq 0 ]; then echo "Recent validate entries:" tail -20 "$DATA_DIR/validate.log" 2>/dev/null || echo " No entries yet. Use: codepal validate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/validate.log" local total=$(wc -l < "$DATA_DIR/validate.log") echo " [Codepal] validate: $input" echo " Saved. Total validate entries: $total" _log "validate" "$input" fi ;; generate) shift if [ $# -eq 0 ]; then echo "Recent generate entries:" tail -20 "$DATA_DIR/generate.log" 2>/dev/null || echo " No entries yet. Use: codepal generate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/generate.log" local total=$(wc -l < "$DATA_DIR/generate.log") echo " [Codepal] generate: $input" echo " Saved. Total generate entries: $total" _log "generate" "$input" fi ;; format) shift if [ $# -eq 0 ]; then echo "Recent format entries:" tail -20 "$DATA_DIR/format.log" 2>/dev/null || echo " No entries yet. Use: codepal format <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/format.log" local total=$(wc -l < "$DATA_DIR/format.log") echo " [Codepal] format: $input" echo " Saved. Total format entries: $total" _log "format" "$input" fi ;; lint) shift if [ $# -eq 0 ]; then echo "Recent lint entries:" tail -20 "$DATA_DIR/lint.log" 2>/dev/null || echo " No entries yet. Use: codepal lint <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/lint.log" local total=$(wc -l < "$DATA_DIR/lint.log") echo " [Codepal] lint: $input" echo " Saved. Total lint entries: $total" _log "lint" "$input" fi ;; explain) shift if [ $# -eq 0 ]; then echo "Recent explain entries:" tail -20 "$DATA_DIR/explain.log" 2>/dev/null || echo " No entries yet. Use: codepal explain <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/explain.log" local total=$(wc -l < "$DATA_DIR/explain.log") echo " [Codepal] explain: $input" echo " Saved. Total explain entries: $total" _log "explain" "$input" fi ;; convert) shift if [ $# -eq 0 ]; then echo "Recent convert entries:" tail -20 "$DATA_DIR/convert.log" 2>/dev/null || echo " No entries yet. Use: codepal convert <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/convert.log" local total=$(wc -l < "$DATA_DIR/convert.log") echo " [Codepal] convert: $input" echo " Saved. Total convert entries: $total" _log "convert" "$input" fi ;; template) shift if [ $# -eq 0 ]; then echo "Recent template entries:" tail -20 "$DATA_DIR/template.log" 2>/dev/null || echo " No entries yet. Use: codepal template <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/template.log" local total=$(wc -l < "$DATA_DIR/template.log") echo " [Codepal] template: $input" echo " Saved. Total template entries: $total" _log "template" "$input" fi ;; diff) shift if [ $# -eq 0 ]; then echo "Recent diff entries:" tail -20 "$DATA_DIR/diff.log" 2>/dev/null || echo " No entries yet. Use: codepal diff <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/diff.log" local total=$(wc -l < "$DATA_DIR/diff.log") echo " [Codepal] diff: $input" echo " Saved. Total diff entries: $total" _log "diff" "$input" fi ;; preview) shift if [ $# -eq 0 ]; then echo "Recent preview entries:" tail -20 "$DATA_DIR/preview.log" 2>/dev/null || echo " No entries yet. Use: codepal preview <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/preview.log" local total=$(wc -l < "$DATA_DIR/preview.log") echo " [Codepal] preview: $input" echo " Saved. Total preview entries: $total" _log "preview" "$input" fi ;; fix) shift if [ $# -eq 0 ]; then echo "Recent fix entries:" tail -20 "$DATA_DIR/fix.log" 2>/dev/null || echo " No entries yet. Use: codepal fix <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/fix.log" local total=$(wc -l < "$DATA_DIR/fix.log") echo " [Codepal] fix: $input" echo " Saved. Total fix entries: $total" _log "fix" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: codepal report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Codepal] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown command: $1" echo "Run 'codepal help' for available commands." exit 1 ;; esac
core reference tool
--- name: "core" version: "3.0.0" description: "core reference tool" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [core, reference] category: "devtools" --- # Core core reference tool. No API keys or credentials required — outputs reference documentation only. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # core — Core reference tool. Use when working with core in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="3.0.0" show_help() { cat << 'HELPEOF' core v$VERSION — Core Reference Tool Usage: core <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Core — Overview ## What is Core? Core (core) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with core. ## Key Concepts - Core core principles and fundamentals - How core fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Core Matters Understanding core is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic core concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Core — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the core package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Core — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for core 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Core — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Core — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Core — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Core — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Core — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "core v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: core help"; exit 1 ;; esac
Manage and grow communities with strategies for engagement, content planning, user growth, monetization, and crisis handling.
--- version: "2.0.0" name: Community Manager description: "Community Manager. Use when you need communityhub capabilities. Triggers on: communityhub." 社群运营。社群搭建、活跃度提升、内容规划、用户增长、变现策略、危机处理。Community management toolkit. 社群、运营、私域。 author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills --- # Community Manager 社群运营。社群搭建、活跃度提升、内容规划、用户增长、变现策略、危机处理。Community management toolkit. 社群、运营、私域。 ## Commands - `build` — build - `engage` — engage - `content` — content - `grow` — grow - `monetize` — monetize - `crisis` — crisis ## Usage Run any command with your input to get started. Use `help` to see all available commands. ## About Part of the BytesAgain productivity toolkit. Visit [bytesagain.com](https://bytesagain.com) for more tools. --- 💬 Feedback & Feature Requests: https://bytesagain.com/feedback Powered by BytesAgain | bytesagain.com ## Examples ```bash # Show help communityhub help # Run communityhub run ``` - Run `communityhub help` for commands - No API keys needed ## Output Results go to stdout. Save with `communityhub run > output.txt`. ## Configuration Set `COMMUNITYHUB_DIR` to change data directory. Default: `~/.local/share/communityhub/` FILE:scripts/community.sh #!/usr/bin/env bash set -euo pipefail CMD="-help"; shift 2>/dev/null || true; INPUT="$*" python3 -c ' import sys cmd = sys.argv[1] if len(sys.argv)>1 else "help" inp = " ".join(sys.argv[2:]) if cmd=="welcome": name=inp if inp else "new member" print("Welcome Message Templates for {}:".format(name)) for t in ["Hey {}! Welcome to our community. Introduce yourself!".format(name),"Welcome aboard, {}! Check out #rules and #introductions.".format(name),"Glad to have you, {}! Here are 3 things to do first:\n 1. Read the rules\n 2. Introduce yourself\n 3. Ask questions!".format(name)]: print("\n > {}".format(t)) elif cmd=="rules": rules=["Be respectful and inclusive","No spam or self-promotion without permission","Stay on topic in channels","No NSFW content","Use search before asking","Help others when you can","Report issues to moderators","English only in main channels"] print(" Community Rules Template:") for i,r in enumerate(rules,1): print(" {}. {}".format(i,r)) elif cmd=="engagement": ideas=["Weekly AMA sessions","Member spotlight/shoutouts","Polls and surveys","Content challenges","Feedback Fridays","New member onboarding","Monthly community report","Gamification (roles/badges)"] print(" Engagement Ideas:") for i in ideas: print(" - {}".format(i)) elif cmd=="metrics": print(" Community Health Metrics:") for m in ["DAU/MAU ratio (target: >20%)","Messages per member per week","New member retention (30-day)","Response time to questions","Active contributor % (target: 10%+)","NPS score","Churn rate"]: print(" {} = ___".format(m)) elif cmd=="help": print("Community Manager\n welcome [name] — Welcome message templates\n rules — Community rules template\n engagement — Engagement ideas\n metrics — Health metrics dashboard") else: print("Unknown: "+cmd) print("\nPowered by BytesAgain | bytesagain.com") ' "$CMD" $INPUT FILE:scripts/script.sh #!/usr/bin/env bash # communityhub - Multi-purpose utility tool set -euo pipefail VERSION="2.0.0" DATA_DIR="-${XDG_DATA_HOME:-$HOME/.local/share/communityhub}" DB="$DATA_DIR/data.log" mkdir -p "$DATA_DIR" show_help() { cat << EOF communityhub v$VERSION Multi-purpose utility tool Usage: communityhub <command> [args] Commands: run Execute main function config Configuration status Show status init Initialize list List items add Add entry remove Remove entry search Search export Export data info Show info help Show this help version Show version Data: \$DATA_DIR EOF } _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } cmd_run() { echo " Running: $1" _log "run" "-" } cmd_config() { echo " Config: $DATA_DIR/config.json" _log "config" "-" } cmd_status() { echo " Status: ready" _log "status" "-" } cmd_init() { echo " Initialized in $DATA_DIR" _log "init" "-" } cmd_list() { [ -f "$DB" ] && cat "$DB" || echo " (empty)" _log "list" "-" } cmd_add() { echo "$(date +%Y-%m-%d) $*" >> "$DB"; echo " Added: $*" _log "add" "-" } cmd_remove() { echo " Removed: $1" _log "remove" "-" } cmd_search() { grep -i "$1" "$DB" 2>/dev/null || echo " Not found: $1" _log "search" "-" } cmd_export() { [ -f "$DB" ] && cat "$DB" || echo "No data" _log "export" "-" } cmd_info() { echo " Version: $VERSION | Data: $DATA_DIR" _log "info" "-" } case "-help" in run) shift; cmd_run "$@" ;; config) shift; cmd_config "$@" ;; status) shift; cmd_status "$@" ;; init) shift; cmd_init "$@" ;; list) shift; cmd_list "$@" ;; add) shift; cmd_add "$@" ;; remove) shift; cmd_remove "$@" ;; search) shift; cmd_search "$@" ;; export) shift; cmd_export "$@" ;; info) shift; cmd_info "$@" ;; help|-h) show_help ;; version|-v) echo "communityhub v$VERSION" ;; *) echo "Unknown: $1"; show_help; exit 1 ;; esac FILE:tips.md # Community Manager - tips.md ## Quick Reference
The Go Cloud Development Kit (Go CDK): A library and tools for open cloud development in Go. go cloud, go, aws, azure, cloud, gcp.
--- version: "2.0.0" name: Go Cloud description: "The Go Cloud Development Kit (Go CDK): A library and tools for open cloud development in Go. go cloud, go, aws, azure, cloud, gcp." author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills --- # Cloud SDK Developer workflow automation tool for project lifecycle management. Provides commands for initializing projects, running checks, building, testing, deploying, managing configuration, generating templates, producing documentation, and cleaning build artifacts — all from a single CLI interface. ## Commands | Command | Description | |---------|-------------| | `cloud-sdk init` | Initialize a new project in the current working directory | | `cloud-sdk check` | Run lint, type-check, and test passes against the project | | `cloud-sdk build` | Build the project artifacts | | `cloud-sdk test` | Execute the full test suite | | `cloud-sdk deploy` | Show the deployment pipeline guide (build → test → stage → prod) | | `cloud-sdk config` | Display or manage project configuration (`config.json`) | | `cloud-sdk status` | Check overall project health and status | | `cloud-sdk template <name>` | Generate a code template for the given component name | | `cloud-sdk docs` | Generate project documentation | | `cloud-sdk clean` | Remove build artifacts and temporary files | | `cloud-sdk help` | Show the built-in help message with all commands | | `cloud-sdk version` | Print the current version (v2.0.0) | ## Data Storage All operational data is stored in `~/.local/share/cloud-sdk/` by default. You can override this by setting the `CLOUD_SDK_DIR` environment variable. Key files inside the data directory: - `history.log` — timestamped log of every command executed - `config.json` — project-level configuration (managed via `config` command) The tool respects `XDG_DATA_HOME` if set, falling back to `$HOME/.local/share`. ## Requirements - **Bash** 4.0+ (uses `set -euo pipefail` for strict error handling) - **coreutils** (standard `date`, `mkdir`, `echo`) - No external dependencies or API keys required - Works on Linux and macOS out of the box ## When to Use 1. **Bootstrapping a new project** — run `cloud-sdk init` to set up project scaffolding quickly from the terminal without remembering per-tool init commands 2. **Pre-commit quality gates** — use `cloud-sdk check` as part of a Git pre-commit hook to run lint + type-check + tests before every commit 3. **CI/CD pipeline steps** — chain `cloud-sdk build` and `cloud-sdk test` inside your continuous integration scripts for a consistent, tool-agnostic interface 4. **Deployment checklists** — run `cloud-sdk deploy` to get a guided walkthrough of the build → test → stage → prod pipeline so nothing gets skipped 5. **Housekeeping and cleanup** — execute `cloud-sdk clean` to wipe build artifacts after releases, freeing disk space and resetting state ## Examples ```bash # Initialize a new project in the current directory cloud-sdk init # Run all quality checks (lint + type-check + tests) cloud-sdk check # Build the project cloud-sdk build # Run the test suite cloud-sdk test # View the deployment guide cloud-sdk deploy # Generate a code template for a component called "service" cloud-sdk template service # Generate project documentation cloud-sdk docs # Check project health cloud-sdk status # Clean up build artifacts cloud-sdk clean # Show version cloud-sdk version ``` ## Configuration Set the `CLOUD_SDK_DIR` environment variable to change the data directory: ```bash export CLOUD_SDK_DIR="$HOME/my-project/.cloud-sdk" ``` Default location: `~/.local/share/cloud-sdk/` ## Output All command output goes to stdout. Redirect to a file if needed: ```bash cloud-sdk status > project-health.txt ``` History is automatically logged to `$DATA_DIR/history.log` with timestamps. --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/go_cloud.sh #!/usr/bin/env bash # Go Cloud - inspired by google/go-cloud set -euo pipefail CMD="-help" shift 2>/dev/null || true case "$CMD" in help) echo "Go Cloud" echo "" echo "Commands:" echo " help Help" echo " run Run" echo " info Info" echo " status Status" echo "" echo "Powered by BytesAgain | bytesagain.com" ;; info) echo "Go Cloud v1.0.0" echo "Based on: https://github.com/google/go-cloud" echo "Stars: 9,872+" ;; run) echo "TODO: Implement main functionality" ;; status) echo "Status: ready" ;; *) echo "Unknown: $CMD" echo "Run 'go-cloud help' for usage" exit 1 ;; esac FILE:scripts/script.sh #!/usr/bin/env bash # cloud-sdk - Developer workflow automation tool set -euo pipefail VERSION="2.0.0" DATA_DIR="-${XDG_DATA_HOME:-$HOME/.local/share/cloud-sdk}" DB="$DATA_DIR/data.log" mkdir -p "$DATA_DIR" show_help() { cat << EOF cloud-sdk v$VERSION Developer workflow automation tool Usage: cloud-sdk <command> [args] Commands: init Initialize project check Run checks build Build project test Run tests deploy Deploy guide config Configuration status Project status template Code template docs Documentation clean Clean artifacts help Show this help version Show version Data: \$DATA_DIR EOF } _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } cmd_init() { echo " Project initialized in $(pwd)" _log "init" "-" } cmd_check() { echo " Running lint + type check + tests..." _log "check" "-" } cmd_build() { echo " Building..." _log "build" "-" } cmd_test() { echo " Running test suite..." _log "test" "-" } cmd_deploy() { echo " Deploy: build -> test -> stage -> prod" _log "deploy" "-" } cmd_config() { echo " Config: $DATA_DIR/config.json" _log "config" "-" } cmd_status() { echo " Status: checking project health..." _log "status" "-" } cmd_template() { echo " Template for: $1" _log "template" "-" } cmd_docs() { echo " Generating docs..." _log "docs" "-" } cmd_clean() { echo " Cleaned build artifacts" _log "clean" "-" } case "-help" in init) shift; cmd_init "$@" ;; check) shift; cmd_check "$@" ;; build) shift; cmd_build "$@" ;; test) shift; cmd_test "$@" ;; deploy) shift; cmd_deploy "$@" ;; config) shift; cmd_config "$@" ;; status) shift; cmd_status "$@" ;; template) shift; cmd_template "$@" ;; docs) shift; cmd_docs "$@" ;; clean) shift; cmd_clean "$@" ;; help|-h) show_help ;; version|-v) echo "cloud-sdk v$VERSION" ;; *) echo "Unknown: $1"; show_help; exit 1 ;; esac FILE:tips.md # Tips for Go Cloud ## Quick Start 1. Run `go-cloud help` to see available commands 2. Most commands output to stdout or generate files ## Source Based on [google/go-cloud](https://github.com/google/go-cloud) - 9,872+ GitHub stars, Language: Go, License: Apache-2.0
Chrome Dev Editor is a developer tool for building apps on the Chrome platform - Chrome Apps and Web browser-devtools.
--- version: "2.0.0" name: Chromedeveditor description: "Chrome Dev Editor is a developer tool for building apps on the Chrome platform - Chrome Apps and Web browser-devtools." author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills --- # Chromedeveditor Chrome Dev Editor is a developer tool for building apps on the Chrome platform - Chrome Apps and Web Apps, in JavaScript or Dart. (NO LONGER IN ACTIVE DEVELOPMENT) ## Commands - `help` - Help - `run` - Run - `info` - Info - `status` - Status ## Features - Core functionality from googlearchive/browser-devtools ## Usage Run any command: `browser-devtools <command> [args]` --- 💬 Feedback & Feature Requests: https://bytesagain.com/feedback Powered by BytesAgain | bytesagain.com ## Examples ```bash # Show help browser-devtools help # Run browser-devtools run ``` - Run `browser-devtools help` for all commands ## Output Results go to stdout. Save with `browser-devtools run > output.txt`. ## Output Results go to stdout. Save with `browser-devtools run > output.txt`. FILE:scripts/chromedeveditor.sh #!/usr/bin/env bash # Chromedeveditor - inspired by googlearchive/chromedeveditor set -euo pipefail CMD="-help" shift 2>/dev/null || true case "$CMD" in help) echo "Chromedeveditor" echo "" echo "Commands:" echo " help Help" echo " run Run" echo " info Info" echo " status Status" echo "" echo "Powered by BytesAgain | bytesagain.com" ;; info) echo "Chromedeveditor v1.0.0" echo "Based on: https://github.com/googlearchive/chromedeveditor" echo "Stars: 2,919+" ;; run) echo "TODO: Implement main functionality" ;; status) echo "Status: ready" ;; *) echo "Unknown: $CMD" echo "Run 'chromedeveditor help' for usage" exit 1 ;; esac FILE:scripts/script.sh #!/usr/bin/env bash # browser-devtools - Multi-purpose utility tool set -euo pipefail VERSION="2.0.0" DATA_DIR="-${XDG_DATA_HOME:-$HOME/.local/share/browser-devtools}" DB="$DATA_DIR/data.log" mkdir -p "$DATA_DIR" show_help() { cat << EOF browser-devtools v$VERSION Multi-purpose utility tool Usage: browser-devtools <command> [args] Commands: run Execute main function config Configuration status Show status init Initialize list List items add Add entry remove Remove entry search Search export Export data info Show info help Show this help version Show version Data: \$DATA_DIR EOF } _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } cmd_run() { echo " Running: $1" _log "run" "-" } cmd_config() { echo " Config: $DATA_DIR/config.json" _log "config" "-" } cmd_status() { echo " Status: ready" _log "status" "-" } cmd_init() { echo " Initialized in $DATA_DIR" _log "init" "-" } cmd_list() { [ -f "$DB" ] && cat "$DB" || echo " (empty)" _log "list" "-" } cmd_add() { echo "$(date +%Y-%m-%d) $*" >> "$DB"; echo " Added: $*" _log "add" "-" } cmd_remove() { echo " Removed: $1" _log "remove" "-" } cmd_search() { grep -i "$1" "$DB" 2>/dev/null || echo " Not found: $1" _log "search" "-" } cmd_export() { [ -f "$DB" ] && cat "$DB" || echo "No data" _log "export" "-" } cmd_info() { echo " Version: $VERSION | Data: $DATA_DIR" _log "info" "-" } case "-help" in run) shift; cmd_run "$@" ;; config) shift; cmd_config "$@" ;; status) shift; cmd_status "$@" ;; init) shift; cmd_init "$@" ;; list) shift; cmd_list "$@" ;; add) shift; cmd_add "$@" ;; remove) shift; cmd_remove "$@" ;; search) shift; cmd_search "$@" ;; export) shift; cmd_export "$@" ;; info) shift; cmd_info "$@" ;; help|-h) show_help ;; version|-v) echo "browser-devtools v$VERSION" ;; *) echo "Unknown: $1"; show_help; exit 1 ;; esac FILE:tips.md # Tips for Chromedeveditor ## Quick Start 1. Run `chromedeveditor help` to see available commands 2. Most commands output to stdout or generate files ## Source Based on [googlearchive/chromedeveditor](https://github.com/googlearchive/chromedeveditor) - 2,919+ GitHub stars, Language: Dart, License: BSD-3-Clause
A delightful community-driven framework for managing your bash configuration, and an auto-update too oh my bash, shell, bash-configuration, bash-themes.
--- version: "2.0.0" name: Oh My Bash description: "A delightful community-driven framework for managing your bash configuration, and an auto-update too oh my bash, shell, bash-configuration, bash-themes." author: BytesAgain homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills --- # Oh My Bash A delightful community-driven framework for managing your bash configuration, and an auto-update tool so that makes it easy to keep up with the latest updates from the community. ## Commands - `help` - Help - `run` - Run - `info` - Info - `status` - Status ## Features - Core functionality from ohmybash/bash-themes ## Usage Run any command: `bash-themes <command> [args]` --- 💬 Feedback & Feature Requests: https://bytesagain.com/feedback Powered by BytesAgain | bytesagain.com ## Examples ```bash # Show help bash-themes help # Run bash-themes run ``` - Run `bash-themes help` for all commands - Run `bash-themes help` for all commands ## Configuration Set `BASH_THEMES_DIR` to change data directory. Default: `~/.local/share/bash-themes/` FILE:scripts/oh_my_bash.sh #!/usr/bin/env bash # Oh My Bash - inspired by ohmybash/oh-my-bash set -euo pipefail CMD="-help" shift 2>/dev/null || true case "$CMD" in help) echo "Oh My Bash" echo "" echo "Commands:" echo " help Help" echo " run Run" echo " info Info" echo " status Status" echo "" echo "Powered by BytesAgain | bytesagain.com" ;; info) echo "Oh My Bash v1.0.0" echo "Based on: https://github.com/ohmybash/oh-my-bash" echo "Stars: 7,318+" ;; run) echo "TODO: Implement main functionality" ;; status) echo "Status: ready" ;; *) echo "Unknown: $CMD" echo "Run 'oh-my-bash help' for usage" exit 1 ;; esac FILE:scripts/script.sh #!/usr/bin/env bash # bash-themes - Developer workflow automation tool set -euo pipefail VERSION="2.0.0" DATA_DIR="-${XDG_DATA_HOME:-$HOME/.local/share/bash-themes}" DB="$DATA_DIR/data.log" mkdir -p "$DATA_DIR" show_help() { cat << EOF bash-themes v$VERSION Developer workflow automation tool Usage: bash-themes <command> [args] Commands: init Initialize project check Run checks build Build project test Run tests deploy Deploy guide config Configuration status Project status template Code template docs Documentation clean Clean artifacts help Show this help version Show version Data: \$DATA_DIR EOF } _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } cmd_init() { echo " Project initialized in $(pwd)" _log "init" "-" } cmd_check() { echo " Running lint + type check + tests..." _log "check" "-" } cmd_build() { echo " Building..." _log "build" "-" } cmd_test() { echo " Running test suite..." _log "test" "-" } cmd_deploy() { echo " Deploy: build -> test -> stage -> prod" _log "deploy" "-" } cmd_config() { echo " Config: $DATA_DIR/config.json" _log "config" "-" } cmd_status() { echo " Status: checking project health..." _log "status" "-" } cmd_template() { echo " Template for: $1" _log "template" "-" } cmd_docs() { echo " Generating docs..." _log "docs" "-" } cmd_clean() { echo " Cleaned build artifacts" _log "clean" "-" } case "-help" in init) shift; cmd_init "$@" ;; check) shift; cmd_check "$@" ;; build) shift; cmd_build "$@" ;; test) shift; cmd_test "$@" ;; deploy) shift; cmd_deploy "$@" ;; config) shift; cmd_config "$@" ;; status) shift; cmd_status "$@" ;; template) shift; cmd_template "$@" ;; docs) shift; cmd_docs "$@" ;; clean) shift; cmd_clean "$@" ;; help|-h) show_help ;; version|-v) echo "bash-themes v$VERSION" ;; *) echo "Unknown: $1"; show_help; exit 1 ;; esac FILE:tips.md # Tips for Oh My Bash ## Quick Start 1. Run `oh-my-bash help` to see available commands 2. Most commands output to stdout or generate files ## Source Based on [ohmybash/oh-my-bash](https://github.com/ohmybash/oh-my-bash) - 7,318+ GitHub stars, Language: Shell, License: MIT