bash-instruct-55k / generate.py
Frost2o24's picture
Bind params per-example; add arg-fidelity gate + NL diversifier
4d263b4 verified
Raw
History Blame Contribute Delete
120 kB
#!/usr/bin/env python3
"""
Bash instruction-tuning dataset generator.
Design:
* bash_dataset.jsonl is GROUND TRUTH. progress.json is a derived snapshot
recomputed from the jsonl on every load -> resume is drift-proof.
* Recipe engine: each recipe family emits (nl, bash) with randomized phrasing
+ concrete params from shared pools. Quotas + per-utility cap + dedup +
`bash -n` syntax check are all enforced here.
* Output is appended after every batch; nothing is held in memory to the end.
CLI:
python generate.py status # report where we stand
python generate.py plan # quota table + what's short
python generate.py run [--batch N] [--batches K] [--target T]
python generate.py validate-all # re-run bash -n over the whole file
"""
import json, os, sys, random, hashlib, subprocess, argparse, tempfile, shutil
from argcheck import arg_mismatch
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "bash_dataset.jsonl")
PROG = os.path.join(HERE, "progress.json")
VALID_DIR = os.path.join(HERE, "._valid")
BASH = shutil.which("bash") or r"C:\Users\User\AppData\Local\Programs\Git\usr\bin\bash.exe"
TARGET_TOTAL = 55000
CAT_SHARE = {"single": 0.40, "pipeline": 0.35, "script": 0.25}
CAT_TARGET = {c: int(round(TARGET_TOTAL * s)) for c, s in CAT_SHARE.items()}
UTIL_CAP = int(TARGET_TOTAL * 0.04) # 2200
# Equivalent system prompts; one is chosen per row so the model doesn't overfit
# to a single exact string. Each entry's "final form" is a chat messages array.
SYSTEM_PROMPTS = [
"You are a Bash expert.",
"You are a helpful assistant that writes correct, idiomatic Bash commands.",
"You are a Linux shell expert. Respond with Bash only.",
"You translate natural-language requests into correct Bash commands.",
"You are a command-line assistant specializing in Bash and GNU coreutils.",
]
# Guaranteed minimum count per utility for the info/system commands that small
# models tend to fumble. Floors are filled preferentially before normal quota
# filling. Values reflect how much genuine, non-templated variety each command
# actually supports (uptime/hostname have small command spaces).
MIN_UTIL = {
"vmstat": 150, "pstree": 150, "nice": 150, "netstat": 150, "renice": 150,
"lsof": 150, "journalctl": 140, "ss": 120, "w": 100, "iostat": 90,
"dmesg": 70, "free": 55, "uptime": 28, "hostname": 24,
}
# --------------------------------------------------------------------------
# shared pools
# --------------------------------------------------------------------------
# pools are generated from realistic stems so combinatorial capacity is large
# while every token stays plausible (real-looking filenames, dirs, hosts, ...).
_STEMS = ["report","data","server","access","error","backup","config","users",
"results","dump","metrics","debug","auth","build","test","output","export",
"invoice","order","customer","product","sales","event","audit","session",
"request","response","payload","summary","archive","index","catalog",
"inventory","transaction","payment","account","profile","notes","changelog",
"release","migration","schema","credentials","settings","manifest"]
_TEXT_EXT = ["txt","csv","md","json","log","tsv","yaml","conf","ini"]
_ANY_EXT = ["txt","log","csv","json","md","py","sh","tmp","bak","conf","yaml","xml",
"html","css","js","jpg","png","pdf","gz","old","sql","tar.gz","zip"]
_LOG_STEMS = ["server","access","error","output","metrics","debug","auth","build",
"app","nginx-access","nginx-error","syslog","kern","cron","mail","gc",
"worker","api","gateway","scheduler","ingest","request","audit"]
def _mk(stems, exts):
return sorted({f"{s}.{e}" for s in stems for e in exts})
FILES = _mk(_STEMS, _ANY_EXT) # ~1000
LOGFILES = sorted({f"{s}.log" for s in _LOG_STEMS} | {"syslog","messages","dmesg.log"})
TEXTFILES = _mk(_STEMS, _TEXT_EXT) # ~400
CSVFILES = _mk(["data","inventory","sales","orders","users","products","export",
"customers","transactions","metrics","report"], ["csv","tsv"])
DIRNAMES = ["src","logs","backup","data","tmp","project","dist","build","config",
"assets","docs","reports","uploads","cache","public","scripts","vendor",
"images","media","bin","lib","tests","include","static","templates",
"migrations","fixtures","downloads","releases","artifacts","modules"]
ABSDIRS = ["/var/log","/etc/nginx","/opt/app","/srv/www","/home/deploy","/var/www",
"/usr/local/bin","/etc/apache2","/var/lib/mysql","/mnt/data","/srv/data",
"/home/alice","/var/cache","/opt/scripts","/data/uploads"]
DIRS = DIRNAMES + ABSDIRS
SDIRS = DIRNAMES
PATTERNS = ["ERROR","WARNING","TODO","FIXME","404","500","403","502","failed",
"timeout","null","DEBUG","exception","warning:","deprecated",
"Connection refused","OutOfMemory","segfault","permission denied","fatal",
"panic","retry","unauthorized","not found","disk full","refused","denied",
"SIGTERM","traceback","rejected","dropped","throttled","expired","invalid",
"critical","unreachable","corrupt","stale","overflow"]
WORDS = ["localhost","admin","root","password","GET","POST","PUT","DELETE","session",
"cookie","token","user_id","email","https","http","cron","kernel","staging",
"production","enabled","disabled","true","false","warning","info","debug",
"127.0.0.1","0.0.0.0","success","pending","active","inactive"]
EXTS = ["txt","log","csv","json","md","py","sh","tmp","bak","conf","yaml","xml",
"html","css","js","jpg","png","gif","pdf","gz","old","sql","zip","cache"]
USERS = ["deploy","www-data","alice","bob","postgres","nginx","jenkins","ubuntu",
"carol","git","backup","dave","erin","mysql","redis","ec2-user","admin",
"svc-app","operator","tomcat"]
GROUPS = ["www-data","developers","staff","docker","sudo","admin","deploy","users",
"wheel","operators","mysql","backup"]
PROCS = ["nginx","node","python","python3","java","mysqld","postgres","redis-server",
"sshd","apache2","dockerd","gunicorn","celery","php-fpm","containerd","mongod",
"rabbitmq","elasticsearch","memcached","haproxy","cron","systemd","chrome",
"vim","tmux"]
SERVICES = ["nginx","docker","ssh","sshd","postgresql","mysql","mariadb","redis",
"cron","apache2","firewalld","fail2ban","prometheus","grafana-server",
"elasticsearch","rabbitmq","memcached","haproxy","containerd","chronyd",
"systemd-networkd","mongod"]
PORTS = [22,80,443,3306,5432,6379,8080,8000,3000,5000,9090,25,53,9200,27017,11211,
5672,15672,9000,8443,25565,2379]
PKGS = ["nginx","htop","git","curl","vim","docker.io","python3-pip","tmux","jq",
"tree","ncdu","net-tools","build-essential","unzip","ripgrep","wget","nmap",
"tcpdump","sysstat","iotop","strace","rsync","zip","postgresql-client",
"redis-tools","fzf","bat","fd-find","htop"]
_SUB = ["api","www","db01","db02","cache","registry","cdn","mail","git","app01",
"web01","proxy","auth","staging","monitor","backup"]
_DOM = ["example.com","example.org","internal","local","corp.net","service.io"]
HOSTS = sorted({f"{s}.{d}" for s in _SUB for d in _DOM}
| {"192.168.1.10","10.0.0.5","172.16.0.20","8.8.8.8","1.1.1.1",
"github.com","github.io","localhost"})
COUNTS = [3,5,10,15,20,25,30,40,50,100,200,500,1000]
DAYS = [1,2,3,5,7,10,14,21,30,60,90,180]
SIZES = ["100M","500M","1G","+10M","+50M","+100M","+500M","10k","100k","+1G","+2G","-1M"]
BRANCHES = ["main","develop","feature/login","feature/search","release/1.2",
"release/2.0","hotfix/crash","hotfix/security","staging","bugfix/auth"]
def R(seq): return random.choice(seq)
def pick(*variants): return random.choice(variants)
# --------------------------------------------------------------------------
# recipe registry
# --------------------------------------------------------------------------
RECIPES = [] # {"fn":..., "category":..., "utility":..., "weight":...}
# High-capacity families are weighted up so recipe selection concentrates on
# them instead of wasting attempts colliding on saturated tiny recipes.
HIGHCAP = {
# pipeline
"p_freqtop","p_catpipe","p_procpipe","p_netpipe","p_logscan","p_diskpipe",
"p_find_xargs","p_grep_count","p_awk_pipe","p_curl","p_chain","p_cmdsub",
"p_redir","p_du_sort","p_ls","p_sed",
# single
"r_grep","r_find","r_sed","r_awk","r_curl","r_journalctl","r_systemctl",
"r_chmod","r_chown","r_cp","r_mv","r_tar","r_fileq","r_ls","r_git_misc",
# script
"s_fileproc","s_backup2","s_retry2","s_findclean2","s_getopts2","s_parallel",
"s_envcheck","s_dbdump","s_hosts_iter","s_funcs2",
"s_for_big","s_while_big","s_if_big","s_case_big","s_func_big","s_report_big",
# info/system utilities (high-capacity idiomatic families)
"r_vmstat2","r_iostat2","r_free2","r_uptime2","r_w2","r_hostname2",
"r_pstree2","r_dmesg2","r_netstat2","r_nice2","r_lsof","r_ss",
}
def recipe(category, utility):
def deco(fn):
RECIPES.append({"fn": fn, "category": category, "utility": utility,
"weight": 12 if fn.__name__ in HIGHCAP else 1})
return fn
return deco
def L(*lines):
"""join script lines with real newlines"""
return "\n".join(lines)
import re as _re
# De-concentrate the dominant "Write a script that ..." opening: every such
# request is remapped to one of several equivalents (the relative clause is
# reused verbatim, so grammar stays correct). Cuts the single-prefix share ~7x.
_SCRIPT_LEADS = [
"Write a script that {c}.",
"Write a Bash script that {c}.",
"Write a shell script that {c}.",
"Create a script that {c}.",
"I need a script that {c}.",
"Write me a script that {c}.",
"Can you write a script that {c}?",
"Write a small script that {c}.",
]
_SW = _re.compile(r'^write a script that (.+?)\.?$', _re.IGNORECASE)
def diversify_nl(nl):
m = _SW.match(nl)
if not m:
return nl
clause = m.group(1)
lead = random.choice(_SCRIPT_LEADS)
return lead.format(c=clause, C=clause[0].upper()+clause[1:])
# ==========================================================================
# SINGLE-COMMAND RECIPES
# ==========================================================================
@recipe("single","ls")
def r_ls():
d = R(DIRS)
return pick(
(f"List all files in {d}, including hidden ones, in long format.", f"ls -la {d}"),
(f"Show the contents of the {d} directory sorted by modification time, newest first.", f"ls -lt {d}"),
(f"How do I list files in {d} sorted by size?", f"ls -lS {d}"),
(f"give me a human-readable long listing of {d}", f"ls -lh {d}"),
(f"List only directories inside {d}.", f"ls -d {d}/*/"),
(f"Show a recursive listing of {d}.", f"ls -R {d}"),
)
@recipe("single","cp")
def r_cp():
a,b = R(FILES), R(SDIRS)
return pick(
(f"Copy {a} into the {b} directory.", f"cp {a} {b}/"),
(f"Make a backup copy of {a} called {a}.bak", f"cp {a} {a}.bak"),
(f"copy the whole {b} folder to {b}_copy recursively", f"cp -r {b} {b}_copy"),
(f"Copy {a} to {b}/ but keep the original timestamps and permissions.", f"cp -p {a} {b}/"),
(f"Copy {a} into {b} only if it's newer than what's there.", f"cp -u {a} {b}/"),
)
@recipe("single","mv")
def r_mv():
a = R(FILES); d = R(SDIRS); e = R(EXTS)
return pick(
(f"Rename {a} to {a}.old", f"mv {a} {a}.old"),
(f"Move {a} into the {d} folder.", f"mv {a} {d}/"),
(f"move all .{e} files into the {d} directory", f"mv *.{e} {d}/"),
(f"Rename {a} to {a}.old without overwriting if the target already exists.", f"mv -n {a} {a}.old"),
)
@recipe("single","rm")
def r_rm():
d = R(SDIRS); f = R(FILES)
return pick(
(f"Delete all .tmp files in the current directory (prompt before each removal to be safe).", "rm -i *.tmp"),
(f"Remove the empty directory {d}.", f"rmdir {d}"),
(f"Force-remove the {d} directory and everything in it. (Careful: this is destructive and cannot be undone.)", f"rm -rf {d}"),
(f"Delete {f} but ask for confirmation first.", f"rm -i {f}"),
)
@recipe("single","mkdir")
def r_mkdir():
d = R(SDIRS)
return pick(
(f"Create a directory called {d}.", f"mkdir {d}"),
(f"Make the nested directory {d}/2026/logs, creating parents as needed.", f"mkdir -p {d}/2026/logs"),
(f"create three folders at once: src, tests and docs", "mkdir src tests docs"),
(f"Make a directory {d} with permissions 700.", f"mkdir -m 700 {d}"),
)
@recipe("single","touch")
def r_touch():
f = R(FILES); g = R(FILES)
return pick(
(f"Create an empty file named {f}.", f"touch {f}"),
(f"Update the modification time of {g} to now.", f"touch {g}"),
(f"create empty files log1.txt log2.txt log3.txt in one go", "touch log{1..3}.txt"),
)
@recipe("single","cat")
def r_cat():
f = R(TEXTFILES)
return pick(
(f"Print the contents of {f} to the terminal.", f"cat {f}"),
(f"Show {f} with line numbers.", f"cat -n {f}"),
(f"Concatenate part1.txt and part2.txt into whole.txt", "cat part1.txt part2.txt > whole.txt"),
(f"display {f} showing tabs and line endings", f"cat -A {f}"),
)
@recipe("single","head")
def r_head():
f,n = R(LOGFILES), R(COUNTS)
return pick(
(f"Show the first {n} lines of {f}.", f"head -n {n} {f}"),
(f"what are the top {n} lines in {f}?", f"head -n {n} {f}"),
(f"Print everything in {f} except the last {n} lines.", f"head -n -{n} {f}"),
)
@recipe("single","tail")
def r_tail():
f,n = R(LOGFILES), R(COUNTS)
return pick(
(f"Show the last {n} lines of {f}.", f"tail -n {n} {f}"),
(f"Follow {f} live as new lines are appended.", f"tail -f {f}"),
(f"keep watching {f} for new entries and start from the last {n} lines", f"tail -n {n} -f {f}"),
(f"Print {f} starting from line {n} to the end.", f"tail -n +{n} {f}"),
)
@recipe("single","chmod")
def r_chmod():
f = R(["deploy.sh","main.py","backup.sh","run.sh"]+FILES); cd = R(SDIRS)
return pick(
(f"Make {f} executable.", f"chmod +x {f}"),
(f"Set {f} to permissions 644.", f"chmod 644 {f}"),
(f"Recursively make everything in {cd} readable and writable by the owner only.", f"chmod -R 600 {cd}"),
(f"give the owner rwx and everyone else read on {f}", f"chmod 744 {f}"),
(f"Remove write permission for group and others on {f}.", f"chmod go-w {f}"),
)
@recipe("single","chown")
def r_chown():
f = R(FILES); u = R(USERS); g = R(GROUPS); d = R(SDIRS)
return pick(
(f"Change the owner of {f} to {u}.", f"sudo chown {u} {f}"),
(f"Recursively set owner and group of {d} to {u}:{g}.", f"sudo chown -R {u}:{g} {d}"),
(f"change just the group of {f} to {g}", f"sudo chgrp {g} {f}"),
)
@recipe("single","find")
def r_find():
d = R(DIRS); e = R(EXTS); sz = R(SIZES); dd = R(DAYS); sub = R(SDIRS); u = R(USERS)
return pick(
(f"Find all .{e} files under {d}.", f"find {d} -type f -name '*.{e}'"),
(f"Find files in {d} larger than {sz}.", f"find {d} -type f -size {sz}"),
(f"locate files under {d} modified in the last {dd} days", f"find {d} -type f -mtime -{dd}"),
(f"Find empty files in {d}.", f"find {d} -type f -empty"),
(f"Find directories named {sub} anywhere under {d}.", f"find {d} -type d -name '{sub}'"),
(f"Find files in {d} owned by {u}.", f"find {d} -type f -user {u}"),
)
@recipe("single","grep")
def r_grep():
p,f = R(PATTERNS), R(LOGFILES); d = R(DIRS)
return pick(
(f"Search {f} for lines containing '{p}'.", f"grep '{p}' {f}"),
(f"Case-insensitively find '{p}' in {f}.", f"grep -i '{p}' {f}"),
(f"Count how many lines in {f} match '{p}'.", f"grep -c '{p}' {f}"),
(f"recursively search {d} for '{p}' and show line numbers", f"grep -rn '{p}' {d}"),
(f"Show lines in {f} that do NOT contain '{p}'.", f"grep -v '{p}' {f}"),
(f"Find '{p}' in {f} plus 3 lines of context around each match.", f"grep -C 3 '{p}' {f}"),
(f"List just the filenames under {d} that contain '{p}'.", f"grep -rl '{p}' {d}"),
)
@recipe("single","sed")
def r_sed():
f = R(TEXTFILES)
a,b = R(WORDS), R(WORDS)
return pick(
(f"Replace every occurrence of '{a}' with '{b}' in {f} and print the result.", f"sed 's/{a}/{b}/g' {f}"),
(f"Edit {f} in place, replacing '{a}' with '{b}'.", f"sed -i 's/{a}/{b}/g' {f}"),
(f"delete all blank lines from {f}", f"sed '/^$/d' {f}"),
(f"Print only lines 10 through 20 of {f}.", f"sed -n '10,20p' {f}"),
(f"Delete the first line of {f} in place.", f"sed -i '1d' {f}"),
)
@recipe("single","awk")
def r_awk():
f = R(["data.csv","inventory.csv","access.log","metrics.log"])
col = R([1,2,3,4])
return pick(
(f"Print the {col}nd column of {f} (whitespace separated).", f"awk '{{print ${col}}}' {f}"),
(f"Print column {col} of the comma-separated file {f}.", f"awk -F, '{{print ${col}}}' {f}"),
(f"Sum up the values in column {col} of {f}.", f"awk '{{sum+=${col}}} END{{print sum}}' {f}"),
(f"print lines of {f} where column {col} is greater than 100", f"awk '${col} > 100' {f}"),
(f"Print the number of fields on each line of {f}.", f"awk '{{print NF}}' {f}"),
)
@recipe("single","sort")
def r_sort():
f = R(TEXTFILES)
return pick(
(f"Sort {f} alphabetically.", f"sort {f}"),
(f"Sort {f} numerically in reverse order.", f"sort -nr {f}"),
(f"Sort {f} and remove duplicate lines.", f"sort -u {f}"),
(f"sort {f} by the 2nd column numerically", f"sort -k2 -n {f}"),
)
@recipe("single","uniq")
def r_uniq():
f = R(TEXTFILES)
return pick(
(f"Remove adjacent duplicate lines from the already-sorted {f}.", f"uniq {f}"),
(f"Count occurrences of each unique line in {f} (assume it's sorted).", f"uniq -c {f}"),
(f"show only the lines in {f} that appear more than once", f"uniq -d {f}"),
)
@recipe("single","wc")
def r_wc():
f = R(FILES)
return pick(
(f"Count the number of lines in {f}.", f"wc -l {f}"),
(f"How many words are in {f}?", f"wc -w {f}"),
(f"count the bytes in {f}", f"wc -c {f}"),
)
@recipe("single","cut")
def r_cut():
f = R(["data.csv","inventory.csv","users.txt","/etc/passwd"])
return pick(
(f"Extract the first field of {f} using comma as the delimiter.", f"cut -d, -f1 {f}"),
(f"Get fields 1 and 3 from {f}, colon separated.", f"cut -d: -f1,3 {f}"),
(f"cut out the first 10 characters of each line in {f}", f"cut -c1-10 {f}"),
)
@recipe("single","tr")
def r_tr():
f = R(TEXTFILES)
return pick(
(f"Convert the contents of {f} to uppercase.", f"tr 'a-z' 'A-Z' < {f}"),
(f"Squeeze repeated spaces into a single space in {f}.", f"tr -s ' ' < {f}"),
(f"delete all digits from {f}", f"tr -d '0-9' < {f}"),
)
@recipe("single","ps")
def r_ps():
psu = R(USERS)
return pick(
("Show all running processes with full details.", "ps aux"),
("List processes in a tree/hierarchy format.", "ps -ef --forest"),
(f"Show all processes for the user {psu}.", f"ps -u {psu}"),
("Display the top memory-consuming processes.", "ps aux --sort=-%mem"),
)
@recipe("single","kill")
def r_kill():
pid = random.randint(1000,9999)
return pick(
(f"Gracefully terminate the process with PID {pid}.", f"kill {pid}"),
(f"Force-kill process {pid}.", f"kill -9 {pid}"),
(f"send SIGHUP to process {pid} to make it reload its config", f"kill -HUP {pid}"),
)
@recipe("single","pkill")
def r_pkill():
p = R(PROCS); u = R(USERS)
return pick(
(f"Kill all {p} processes by name.", f"pkill {p}"),
(f"Force-kill every process whose name matches {p}.", f"pkill -9 {p}"),
(f"gracefully stop all processes owned by {u}", f"pkill -u {u}"),
)
@recipe("single","pgrep")
def r_pgrep():
p = R(PROCS)
return pick(
(f"Find the PIDs of all {p} processes.", f"pgrep {p}"),
(f"list PIDs and names of processes matching {p}", f"pgrep -a {p}"),
(f"Get the PID of the newest {p} process.", f"pgrep -n {p}"),
)
@recipe("single","df")
def r_df():
return pick(
("Show disk space usage of all mounted filesystems in human-readable form.", "df -h"),
("How much space is left on the root filesystem?", "df -h /"),
("Show filesystem disk usage including inode counts.", "df -i"),
)
@recipe("single","du")
def r_du():
d = R(DIRS)
return pick(
(f"Show the total size of the {d} directory in human-readable form.", f"du -sh {d}"),
(f"list the size of each subdirectory in {d}", f"du -h --max-depth=1 {d}"),
(f"How big is {d} overall?", f"du -sh {d}"),
)
@recipe("single","free")
def r_free():
return pick(
("Show current memory usage in human-readable units.", "free -h"),
("Display memory usage in megabytes.", "free -m"),
("show memory including a total line for RAM plus swap", "free -h -t"),
("Report memory usage refreshing every 2 seconds.", "free -h -s 2"),
)
@recipe("single","uptime")
def r_uptime():
return pick(
("How long has the system been running?", "uptime"),
("Show just the load averages in a pretty form.", "uptime"),
("print uptime in the short 'pretty' format", "uptime -p"),
("When did the system last boot?", "uptime -s"),
)
@recipe("single","uname")
def r_uname():
return pick(
("Print all system information (kernel, hostname, architecture, etc.).", "uname -a"),
("What kernel release is this machine running?", "uname -r"),
("show the machine hardware architecture", "uname -m"),
)
@recipe("single","hostname")
def r_hostname():
return pick(
("Show the system's hostname.", "hostname"),
("Print all the IP addresses assigned to this host.", "hostname -I"),
("what's the fully qualified domain name of this machine?", "hostname -f"),
)
@recipe("single","vmstat")
def r_vmstat():
n = R([1,2,3,5])
c = R([5,10,3])
return pick(
(f"Report virtual memory statistics every {n} seconds, {c} times.", f"vmstat {n} {c}"),
("Show a one-shot summary of virtual memory, processes and CPU.", "vmstat"),
(f"monitor system performance with vmstat every {n} seconds using human-readable units", f"vmstat -S M {n}"),
("Display active/inactive memory breakdown with vmstat.", "vmstat -a"),
)
@recipe("single","iostat")
def r_iostat():
n = R([1,2,5])
return pick(
(f"Show CPU and disk I/O statistics every {n} seconds.", f"iostat {n}"),
("Display extended disk I/O stats in human-readable form.", "iostat -xh"),
(f"report I/O stats {n} times, one per second", f"iostat 1 {n}"),
("Show only device utilization stats, not CPU.", "iostat -d"),
)
@recipe("single","pstree")
def r_pstree():
p = R(PROCS)
return pick(
("Show the process tree with PIDs.", "pstree -p"),
("Display the process hierarchy for user deploy.", "pstree deploy"),
("show the process tree highlighting the current process and its ancestors", "pstree -hp"),
(f"visualize the child processes of {p} as a tree", f"pstree -p $(pgrep -o {p})"),
)
@recipe("single","w")
def r_w():
return pick(
("Show who is logged in and what they are doing.", "w"),
("List logged-in users without the header line.", "w -h"),
("show logged-in users but hide the command column", "w -s"),
)
@recipe("single","who")
def r_who():
return pick(
("List all users currently logged in.", "who"),
("Who am I logged in as on this terminal?", "whoami"),
("show the system boot time using who", "who -b"),
)
@recipe("single","nice")
def r_nice():
return pick(
(f"Start a backup with tar at the lowest CPU priority.", "nice -n 19 tar -czf backup.tar.gz /home/deploy"),
("Run a python script with a nice value of 10.", "nice -n 10 python main.py"),
("launch a compile job at reduced priority so it doesn't hog the CPU", "nice -n 15 make -j4"),
)
@recipe("single","renice")
def r_renice():
pid = random.randint(1000,9999); u = R(USERS)
return pick(
(f"Lower the priority of process {pid} to nice value 10.", f"renice -n 10 -p {pid}"),
(f"Bump process {pid} to a higher priority (nice -5). Requires root.", f"sudo renice -n -5 -p {pid}"),
(f"reduce the priority of all processes owned by {u}", f"renice -n 15 -u {u}"),
)
@recipe("single","lsof")
def r_lsof():
port=R(PORTS); proc=R(PROCS); u=R(USERS); d=R(DIRS); pid=random.randint(500,9000)
nl,b=_F([
(f"lsof -i :{port}", (f"Show which process is using port {port}.",
f"What's bound to port {port}?",f"Find the process listening on port {port}.")),
(f"lsof -i :{port} -t", (f"Print just the PID using port {port}.",
f"Get the bare PID that holds port {port}.")),
(f"lsof -c {proc}", (f"List all files opened by {proc}.",f"Show open files for the {proc} process.")),
(f"lsof -u {u}", (f"Which files does user {u} have open?",f"List open files owned by {u}.")),
(f"lsof -p {pid}", (f"List the files opened by process {pid}.",f"Show what PID {pid} has open.")),
(f"lsof +D {d}", (f"Show every open file under {d}.",f"Which processes have files open in {d}?")),
("lsof -i", ("List all open network connections.","Show every network socket in use.")),
("lsof -i tcp", ("List all open TCP connections.","Show TCP sockets currently in use.")),
("lsof -nP -iTCP -sTCP:LISTEN", ("List listening TCP sockets without resolving names/ports.",
"Show all TCP listeners numerically via lsof.")),
(f"lsof -i :{port} -sTCP:ESTABLISHED", (f"Show established connections on port {port}.",
f"List active (established) sessions on port {port}.")),
])
return nl, b, "lsof"
@recipe("single","ss")
def r_ss():
port=R(PORTS); h=R(HOSTS)
nl,b=_F([
("ss -tlnp", ("List listening TCP sockets with the owning process.",
"Show TCP listeners and their PIDs.","What TCP ports are being listened on, and by what?")),
("ss -ulnp", ("List listening UDP sockets with their processes.","Show UDP listeners numerically.")),
("ss -tulnp", ("List all listening TCP and UDP sockets with programs.",
"Show every listening socket and the process behind it.")),
("ss -t state established", ("Show all established TCP connections.","List active TCP sessions.")),
("ss -s", ("Summarize socket statistics by type.","Show a summary of socket counts.")),
("ss -tan", ("Show all TCP sockets numerically.","List every TCP socket without name resolution.")),
(f"ss -tlnp sport = :{port}", (f"Is anything listening on port {port}?",
f"Show the listener on port {port}.",f"Check what holds port {port} with ss.")),
(f"ss -tn dst {h}", (f"Show TCP connections to {h}.",f"List sessions with destination {h}.")),
(f"ss -tn 'sport = :{port} or dport = :{port}'", (f"Show all TCP sockets touching port {port}.",
f"List connections using port {port} as source or destination.")),
("ss -tp state time-wait", ("Show TCP sockets in the TIME-WAIT state with their process.",
"List connections stuck in TIME-WAIT.")),
])
return nl, b, "ss"
@recipe("single","netstat")
def r_netstat():
return pick(
("List all listening ports and the programs using them.", "netstat -tulpn"),
("Show the kernel routing table.", "netstat -rn"),
("display network interface statistics", "netstat -i"),
)
@recipe("single","dmesg")
def r_dmesg():
return pick(
("Show kernel ring buffer messages with human-readable timestamps.", "dmesg -T"),
("Follow new kernel messages as they arrive.", "dmesg -w"),
("show only kernel error and warning level messages", "dmesg --level=err,warn"),
("Display kernel messages colorized with timestamps.", "dmesg -TL"),
)
@recipe("single","journalctl")
def r_journalctl():
s = R(SERVICES); dd = R(DAYS)
return pick(
(f"Show the systemd journal for the {s} service.", f"journalctl -u {s}"),
(f"Follow live logs for {s}.", f"journalctl -u {s} -f"),
("Show all journal entries since the last boot.", "journalctl -b"),
(f"show {s} logs from the last {dd} days", f"journalctl -u {s} --since '{dd} days ago'"),
("Display kernel messages from the journal with priority error or worse.", "journalctl -k -p err"),
(f"Show the 50 most recent {s} log lines, newest last.", f"journalctl -u {s} -n 50"),
)
@recipe("single","systemctl")
def r_systemctl():
s = R(SERVICES)
return pick(
(f"Restart the {s} service.", f"sudo systemctl restart {s}"),
(f"Check the status of {s}.", f"systemctl status {s}"),
(f"enable {s} to start on boot", f"sudo systemctl enable {s}"),
(f"Is the {s} service currently active?", f"systemctl is-active {s}"),
("List all failed systemd units.", "systemctl --failed"),
(f"reload {s} without a full restart", f"sudo systemctl reload {s}"),
)
@recipe("single","ip")
def r_ip():
return pick(
("Show all network interfaces and their IP addresses.", "ip addr show"),
("Display the routing table.", "ip route"),
("show statistics for all network links", "ip -s link"),
("What's the default gateway?", "ip route | grep default"),
)
@recipe("single","ping")
def r_ping():
h = R(HOSTS)
return pick(
(f"Ping {h} four times and stop.", f"ping -c 4 {h}"),
(f"check if {h} is reachable with 3 pings", f"ping -c 3 {h}"),
)
@recipe("single","curl")
def r_curl():
h = R(HOSTS)
return pick(
(f"Fetch https://{h}/health and print only the HTTP status code.", f"curl -s -o /dev/null -w '%{{http_code}}' https://{h}/health"),
(f"Download https://{h}/file.zip and save it with its remote name.", f"curl -O https://{h}/file.zip"),
(f"send a GET request to https://{h}/api and show the response headers", f"curl -I https://{h}/api"),
(f"POST a JSON body to https://{h}/api/users", f"curl -X POST -H 'Content-Type: application/json' -d '{{\"name\":\"alice\"}}' https://{h}/api/users"),
(f"follow redirects when fetching https://{h}", f"curl -L https://{h}"),
)
@recipe("single","wget")
def r_wget():
h = R(HOSTS)
return pick(
(f"Download https://{h}/archive.tar.gz.", f"wget https://{h}/archive.tar.gz"),
(f"quietly download https://{h}/data.json and save it as data.json", f"wget -q -O data.json https://{h}/data.json"),
(f"Mirror the site https://{h} recursively.", f"wget -r -np https://{h}"),
(f"resume an interrupted download of https://{h}/big.iso", f"wget -c https://{h}/big.iso"),
)
@recipe("single","tar")
def r_tar():
d = R(SDIRS)
return pick(
(f"Create a gzip-compressed archive of the {d} directory.", f"tar -czf {d}.tar.gz {d}"),
(f"Extract archive.tar.gz into the current directory.", "tar -xzf archive.tar.gz"),
(f"List the contents of backup.tar.gz without extracting.", "tar -tzf backup.tar.gz"),
(f"extract backup.tar.gz into the {d} folder", f"tar -xzf backup.tar.gz -C {d}"),
(f"make a bzip2-compressed tarball of {d}", f"tar -cjf {d}.tar.bz2 {d}"),
)
@recipe("single","gzip")
def r_gzip():
f = R(LOGFILES)
return pick(
(f"Compress {f} with gzip.", f"gzip {f}"),
(f"Decompress {f}.gz.", f"gunzip {f}.gz"),
(f"compress {f} but keep the original file too", f"gzip -k {f}"),
)
@recipe("single","zip")
def r_zip():
d = R(SDIRS)
return pick(
(f"Zip up the {d} directory into {d}.zip.", f"zip -r {d}.zip {d}"),
(f"Unzip archive.zip into the current folder.", "unzip archive.zip"),
(f"list the contents of archive.zip without extracting", "unzip -l archive.zip"),
)
@recipe("single","ln")
def r_ln():
f = R(FILES)
return pick(
(f"Create a symbolic link named latest.log pointing to {f}.", f"ln -s {f} latest.log"),
(f"make a symlink to /opt/app/current in your home directory called app", "ln -s /opt/app/current ~/app"),
)
@recipe("single","stat")
def r_stat():
f = R(FILES)
return pick(
(f"Show detailed metadata for {f}.", f"stat {f}"),
(f"Print just the octal permission bits of {f}.", f"stat -c '%a' {f}"),
(f"what's the size of {f} in bytes?", f"stat -c '%s' {f}"),
)
@recipe("single","file")
def r_file():
f = R(FILES); d = R(SDIRS)
return pick(
(f"Determine the file type of {f}.", f"file {f}"),
(f"check the type of every file in {d}", f"file {d}/*"),
)
@recipe("single","date")
def r_date():
return pick(
("Print the current date and time.", "date"),
("Show the current date in YYYY-MM-DD format.", "date +%Y-%m-%d"),
("get the current Unix timestamp", "date +%s"),
("What was the date 7 days ago?", "date -d '7 days ago' +%Y-%m-%d"),
("Print the current time in UTC.", "date -u"),
)
@recipe("single","df_git_status")
def r_git_misc():
br = R(BRANCHES); br2 = R(BRANCHES)
return pick(
("Show the current git status in short form.", "git status -s"),
(f"Create and switch to a new branch called {br}.", f"git checkout -b {br}"),
("Show the last 5 commits as a one-line log.", "git log --oneline -5"),
("Stage all changes and commit with a message.", "git commit -am 'update'"),
(f"Pull the latest changes for the {br2} branch.", f"git pull origin {br2}"),
("Show what changed but hasn't been staged yet.", "git diff"),
("Discard all uncommitted changes in the working tree. (Destructive.)", "git checkout -- ."),
(f"push the current branch and set upstream to origin", "git push -u origin HEAD"),
("Show which files changed in the last commit.", "git show --stat HEAD"),
("Undo the last commit but keep the changes staged.", "git reset --soft HEAD~1"),
)
# relabel utility to git
RECIPES[-1]["utility"] = "git"
@recipe("single","apt")
def r_apt():
p = R(PKGS)
return pick(
(f"Install {p} with apt.", f"sudo apt install -y {p}"),
("Update the package index and upgrade all packages.", "sudo apt update && sudo apt upgrade -y"),
(f"Search apt for packages matching {p}.", f"apt search {p}"),
(f"remove {p} and its config files", f"sudo apt purge -y {p}"),
(f"show info about the {p} package", f"apt show {p}"),
)
@recipe("single","dnf")
def r_dnf():
p = R(PKGS)
return pick(
(f"Install {p} using dnf.", f"sudo dnf install -y {p}"),
("Update all packages with dnf.", "sudo dnf upgrade -y"),
(f"remove the {p} package with yum", f"sudo yum remove -y {p}"),
)
@recipe("single","pacman")
def r_pacman():
p = R(PKGS)
return pick(
(f"Install {p} with pacman.", f"sudo pacman -S {p}"),
("Sync and update all packages on Arch.", "sudo pacman -Syu"),
(f"remove {p} and unneeded dependencies", f"sudo pacman -Rs {p}"),
)
@recipe("single","ssh")
def r_ssh():
h,u = R(HOSTS), R(USERS); port = R(PORTS)
return pick(
(f"SSH into {h} as {u}.", f"ssh {u}@{h}"),
(f"connect to {h} on port {port} as {u}", f"ssh -p {port} {u}@{h}"),
(f"Run 'uptime' on {h} over SSH without an interactive session.", f"ssh {u}@{h} uptime"),
)
@recipe("single","scp")
def r_scp():
h,u,f = R(HOSTS), R(USERS), R(FILES); lf = R(LOGFILES)
return pick(
(f"Copy {f} to {h}'s /tmp directory as {u}.", f"scp {f} {u}@{h}:/tmp/"),
(f"download /var/log/{lf} from {h} to the current dir", f"scp {u}@{h}:/var/log/{lf} ."),
)
@recipe("single","rsync")
def r_rsync():
a,b = R(SDIRS), R(SDIRS)
h = R(HOSTS); u = R(USERS)
return pick(
(f"Sync the {a} directory to {b} preserving attributes.", f"rsync -av {a}/ {b}/"),
(f"Mirror {a} to {h}:/backup deleting files that no longer exist locally.", f"rsync -avz --delete {a}/ {u}@{h}:/backup/"),
(f"do a dry-run rsync of {a} to {b} to see what would change", f"rsync -avn {a}/ {b}/"),
)
@recipe("single","id")
def r_id():
u = R(USERS)
return pick(
(f"Show the user and group IDs for {u}.", f"id {u}"),
("What groups does the current user belong to?", "id -Gn"),
("Print the current user's numeric UID.", "id -u"),
)
@recipe("single","which")
def r_which():
c = R(["python3","node","git","docker","curl","psql"])
return pick(
(f"Where is the {c} binary located?", f"which {c}"),
(f"find the full path of {c} and follow symlinks", f"readlink -f $(which {c})"),
(f"Show the type and location of {c}.", f"type -a {c}"),
)
@recipe("single","mount")
def r_mount():
return pick(
("Show all currently mounted filesystems in a readable table.", "mount | column -t"),
("Mount /dev/sdb1 at /mnt/data.", "sudo mount /dev/sdb1 /mnt/data"),
("unmount /mnt/data", "sudo umount /mnt/data"),
)
@recipe("single","top")
def r_top():
p = R(PROCS)
return pick(
("Run top in batch mode for a single snapshot.", "top -b -n1"),
("Launch an interactive process monitor sorted by CPU.", "top"),
(f"show top output for just the {p} processes", f"top -p $(pgrep -d, {p})"),
)
@recipe("single","env")
def r_env():
return pick(
("Print all environment variables.", "env"),
("Show the value of the PATH environment variable.", "echo $PATH"),
(f"run a command with a temporary env var APP_ENV set to production", "env APP_ENV=production ./deploy.sh"),
)
# ==========================================================================
# PIPELINE RECIPES
# ==========================================================================
@recipe("pipeline","grep")
def p_grep_count():
p,f = R(PATTERNS), R(LOGFILES)
return pick(
(f"Count how many unique IP-like first fields appear in {f}.", f"awk '{{print $1}}' {f} | sort | uniq -c | sort -nr"),
(f"Find the 10 most common '{p}'-related lines in {f}.", f"grep '{p}' {f} | sort | uniq -c | sort -nr | head -n 10"),
(f"How many lines in {f} mention '{p}'?", f"grep -c '{p}' {f} | cat"),
(f"list the distinct error messages in {f}", f"grep -i error {f} | sort -u"),
)
RECIPES[-1]["utility"]="grep"
@recipe("pipeline","ps")
def p_ps_grep():
p = R(PROCS)
return pick(
(f"Find the running {p} processes (excluding the grep itself).", f"ps aux | grep [{p[0]}]{p[1:]}"),
(f"Show the PID and memory of {p} processes.", f"ps aux | grep {p} | grep -v grep | awk '{{print $2, $4}}'"),
("Show the top 5 processes by memory usage.", "ps aux --sort=-%mem | head -n 6"),
("List the top 5 CPU-hungry processes.", "ps aux --sort=-%cpu | head -n 6"),
)
RECIPES[-1]["utility"]="ps"
@recipe("pipeline","du")
def p_du_sort():
d = R(DIRS)
return pick(
(f"Show the 10 largest subdirectories in {d}.", f"du -h {d}/* | sort -rh | head -n 10"),
(f"Find the biggest files under {d}.", f"du -ah {d} | sort -rh | head -n 20"),
(f"which directories under {d} are eating the most space?", f"du -h --max-depth=1 {d} | sort -rh"),
)
RECIPES[-1]["utility"]="du"
@recipe("pipeline","find")
def p_find_xargs():
d = R(DIRS)
e = R(EXTS)
return pick(
(f"Find all .{e} files under {d} and delete them. (Careful: destructive.)", f"find {d} -type f -name '*.{e}' -print0 | xargs -0 rm -f"),
(f"Count total lines across all .{e} files in {d}.", f"find {d} -type f -name '*.{e}' -print0 | xargs -0 cat | wc -l"),
(f"gzip every .log file under {d}", f"find {d} -type f -name '*.log' -print0 | xargs -0 gzip"),
(f"search all .{e} files under {d} for the word TODO", f"find {d} -name '*.{e}' -print0 | xargs -0 grep -l TODO"),
(f"change permissions to 644 on all files under {d}", f"find {d} -type f -print0 | xargs -0 chmod 644"),
)
RECIPES[-1]["utility"]="find"
@recipe("pipeline","cat")
def p_cat_sort():
f = R(TEXTFILES)
return pick(
(f"Show the unique sorted lines of {f}.", f"cat {f} | sort | uniq"),
(f"Count how many times each line appears in {f}, most frequent first.", f"sort {f} | uniq -c | sort -nr"),
(f"get the 5 most common words in {f}", f"cat {f} | tr ' ' '\\n' | sort | uniq -c | sort -nr | head -n 5"),
)
RECIPES[-1]["utility"]="sort"
@recipe("pipeline","awk")
def p_awk_pipe():
f = R(["access.log","metrics.log","data.csv"])
return pick(
(f"Sum the response sizes (column 10) in {f}.", f"awk '{{s+=$10}} END{{print s}}' {f}"),
(f"Show the average of the second column in {f}.", f"awk '{{s+=$2; n++}} END{{print s/n}}' {f}"),
(f"count requests per HTTP status code in {f}", f"awk '{{print $9}}' {f} | sort | uniq -c | sort -nr"),
(f"print the total and count of column 3 in {f}", f"awk '{{sum+=$3; c++}} END{{print sum, c}}' {f}"),
)
RECIPES[-1]["utility"]="awk"
@recipe("pipeline","journalctl")
def p_journal():
s = R(SERVICES)
return pick(
(f"Count error lines in the {s} journal since yesterday.", f"journalctl -u {s} --since yesterday | grep -ic error"),
(f"Show the last 20 warning entries for {s}.", f"journalctl -u {s} -p warning -n 20 --no-pager"),
(f"which {s} log lines mention 'failed'?", f"journalctl -u {s} --no-pager | grep -i failed"),
)
RECIPES[-1]["utility"]="journalctl"
@recipe("pipeline","ss")
def p_ss():
port = R(PORTS)
return pick(
("Count how many established TCP connections there are.", "ss -t state established | tail -n +2 | wc -l"),
(f"How many connections are there to port {port}?", f"ss -tn | grep ':{port}' | wc -l"),
("List the remote IPs with the most open connections.", "ss -tn | awk 'NR>1 {print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head"),
)
RECIPES[-1]["utility"]="ss"
@recipe("pipeline","history")
def p_history():
return pick(
("Show the 10 most frequently used commands from your shell history.", "history | awk '{print $2}' | sort | uniq -c | sort -nr | head -n 10"),
(f"search your command history for anything with 'docker'", "history | grep docker"),
)
RECIPES[-1]["utility"]="history"
@recipe("pipeline","df")
def p_df_awk():
return pick(
("Print the used percentage of the root filesystem as a number.", "df -h / | awk 'NR==2 {print $5}'"),
("Warn if any filesystem is over 90% full.", "df -h | awk 'NR>1 && $5+0 > 90 {print $6, $5}'"),
("show mount points sorted by usage percentage", "df -h | awk 'NR>1 {print $5, $6}' | sort -rn"),
)
RECIPES[-1]["utility"]="df"
@recipe("pipeline","cut")
def p_cut():
return pick(
("List all usernames on the system from /etc/passwd.", "cut -d: -f1 /etc/passwd | sort"),
(f"extract unique domains from the second field of emails.txt", "cut -d@ -f2 emails.txt | sort -u"),
("Show the shells in use and how many users have each.", "cut -d: -f7 /etc/passwd | sort | uniq -c | sort -nr"),
)
RECIPES[-1]["utility"]="cut"
@recipe("pipeline","curl")
def p_curl():
h = R(HOSTS)
return pick(
(f"Fetch JSON from https://{h}/api/users and pretty-print it with jq.", f"curl -s https://{h}/api/users | jq ."),
(f"get the number of items in the JSON array at https://{h}/api/items", f"curl -s https://{h}/api/items | jq 'length'"),
(f"download https://{h}/list.txt and count the lines", f"curl -s https://{h}/list.txt | wc -l"),
(f"extract all the 'name' fields from https://{h}/api/users", f"curl -s https://{h}/api/users | jq -r '.[].name'"),
)
RECIPES[-1]["utility"]="curl"
@recipe("pipeline","ls")
def p_ls():
d = R(DIRS); e = R(EXTS)
return pick(
(f"Count how many files are in {d}.", f"ls -1 {d} | wc -l"),
(f"Find the most recently modified file in {d}.", f"ls -t {d} | head -n 1"),
(f"list only the .{e} files in {d}", f"ls {d} | grep '\\.{e}$'"),
)
RECIPES[-1]["utility"]="ls"
@recipe("pipeline","sed")
def p_sed():
f = R(TEXTFILES)
return pick(
(f"Extract just the email addresses from {f}.", f"grep -oE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+' {f} | sort -u"),
(f"strip leading whitespace from every line of {f} and save to clean.txt", f"sed 's/^[[:space:]]*//' {f} > clean.txt"),
(f"replace tabs with commas in {f} and write to {f}.csv", f"sed 's/\\t/,/g' {f} > {f}.csv"),
)
RECIPES[-1]["utility"]="sed"
@recipe("pipeline","xargs")
def p_xargs():
port = R(PORTS)
return pick(
("Read package names from packages.txt and install them all with apt.", "xargs -a packages.txt sudo apt install -y"),
(f"kill every process listening on port {port}", f"lsof -ti :{port} | xargs -r kill -9"),
("Run 4 parallel gzip jobs over every .log file in the current dir.", "ls *.log | xargs -P4 -n1 gzip"),
)
RECIPES[-1]["utility"]="xargs"
@recipe("pipeline","tar")
def p_tar():
d = R(SDIRS); u = R(USERS); h = R(HOSTS)
return pick(
(f"Archive {d} and pipe it over ssh to back it up on a remote host.", f"tar -czf - {d} | ssh {u}@{h} 'cat > /backup/{d}.tar.gz'"),
(f"count how many files are inside backup.tar.gz", "tar -tzf backup.tar.gz | wc -l"),
)
RECIPES[-1]["utility"]="tar"
@recipe("pipeline","chain")
def p_chain():
d = R(SDIRS); cf = R(FILES)
return pick(
(f"Create the {d} directory if needed and then cd into it.", f"mkdir -p {d} && cd {d}"),
(f"Build the project and only deploy if the build succeeds.", "make build && ./deploy.sh"),
(f"Try to restart nginx, and if that fails, print an error.", "sudo systemctl restart nginx || echo 'nginx restart failed' >&2"),
(f"Run the tests and echo PASS or FAIL depending on the result.", "pytest -q && echo PASS || echo FAIL"),
(f"Check if {cf} exists and cat it, otherwise say it's missing.", f"[ -f {cf} ] && cat {cf} || echo 'not found'"),
(f"Pull latest code and restart the app service.", "git pull && sudo systemctl restart myapp"),
)
RECIPES[-1]["utility"]="chain"
@recipe("pipeline","cmdsub")
def p_cmdsub():
return pick(
("Create a backup file stamped with today's date.", "cp app.json app-$(date +%Y%m%d).json"),
(f"Make a timestamped log directory under logs/.", "mkdir -p logs/$(date +%Y-%m-%d)"),
("Kill the process using the most memory. (Careful.)", "kill $(ps aux --sort=-%mem | awk 'NR==2 {print $2}')"),
("Tar up the current directory into a dated archive.", "tar -czf backup-$(date +%F).tar.gz ."),
("Print how many CPU cores this machine has.", "echo \"Cores: $(nproc)\""),
)
RECIPES[-1]["utility"]="cmdsub"
@recipe("pipeline","free")
def p_free():
return pick(
("Print the percentage of memory currently in use.", "free | awk '/Mem/ {printf \"%.1f%%\\n\", $3/$2*100}'"),
("Show just the amount of free memory in MB.", "free -m | awk '/Mem/ {print $4}'"),
)
RECIPES[-1]["utility"]="free"
@recipe("pipeline","vmstat")
def p_vmstat():
return pick(
("Extract the idle-CPU column from a vmstat snapshot.", "vmstat 1 2 | tail -n1 | awk '{print $15}'"),
("Log vmstat output to a file with timestamps every 5 seconds.", "vmstat 5 | while read line; do echo \"$(date '+%F %T') $line\"; done >> vmstat.log"),
)
RECIPES[-1]["utility"]="vmstat"
@recipe("pipeline","dmesg")
def p_dmesg():
return pick(
("Check dmesg for any out-of-memory killer events.", "dmesg -T | grep -i 'out of memory'"),
("Look for USB-related messages in the kernel log.", "dmesg -T | grep -i usb"),
)
RECIPES[-1]["utility"]="dmesg"
@recipe("pipeline","redir")
def p_redir():
f = R(LOGFILES)
return pick(
(f"Run the backup script, sending stdout and stderr to {f}.", f"./backup.sh > {f} 2>&1"),
(f"Append the current date to {f}.", f"date >> {f}"),
("Discard all output from a noisy command.", "./noisy.sh > /dev/null 2>&1"),
(f"Save errors to error.log and normal output to out.log separately.", "./run.sh > out.log 2> error.log"),
("Feed a here-string into base64.", "base64 <<< 'hello world'"),
)
RECIPES[-1]["utility"]="redirection"
# ==========================================================================
# SCRIPT RECIPES (multi-line)
# ==========================================================================
@recipe("script","for")
def s_for_rename():
e1,e2 = R(["jpeg","JPG","txt","htm"]), R(["jpg","jpg","text","html"])
return (
f"Write a script that renames every .{e1} file in the current directory to .{e2}.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'for f in *.{e1}; do',
' [ -e "$f" ] || continue',
f' mv -- "$f" "${{f%.{e1}}}.{e2}"',
'done')
)
@recipe("script","for")
def s_for_batch():
d = R(SDIRS)
return (
f"Loop over every .log file in {d} and gzip any that are larger than 10MB.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'for f in {d}/*.log; do',
' [ -e "$f" ] || continue',
' if [ "$(stat -c %s "$f")" -gt 10485760 ]; then',
' gzip "$f"',
' echo "compressed $f"',
' fi',
'done')
)
@recipe("script","while")
def s_while_read():
f = R(["hosts.txt","servers.txt","urls.txt"])
return (
f"Read {f} line by line and ping each host once, reporting up or down.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'while IFS= read -r host; do',
' [ -z "$host" ] && continue',
' if ping -c1 -W1 "$host" >/dev/null 2>&1; then',
' echo "$host is UP"',
' else',
' echo "$host is DOWN"',
' fi',
f'done < {f}')
)
@recipe("script","if")
def s_if_disk():
th = R([80,85,90,95])
return (
f"Write a script that alerts if the root filesystem is more than {th}% full.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'threshold={th}',
"usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')",
'if [ "$usage" -gt "$threshold" ]; then',
f' echo "WARNING: root filesystem is ${{usage}}% full (threshold ${{threshold}}%)" >&2',
' exit 1',
'fi',
'echo "Disk usage OK: ${usage}%"')
)
@recipe("script","function")
def s_function_log():
return (
"Write a script with a reusable log() function that prefixes messages with a timestamp and severity.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
"log() {",
' local level="$1"; shift',
' printf \'%s [%s] %s\\n\' "$(date \'+%Y-%m-%d %H:%M:%S\')" "$level" "$*"',
"}",
'log INFO "starting job"',
'log WARN "low disk space"',
'log INFO "done"')
)
@recipe("script","getopts")
def s_getopts():
return (
"Write a script that parses -f (file), -n (count) and -v (verbose) options with getopts.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
"verbose=0",
"file=\"\"",
"count=10",
'usage() { echo "usage: $0 -f FILE [-n COUNT] [-v]" >&2; exit 1; }',
'while getopts ":f:n:v" opt; do',
' case "$opt" in',
' f) file="$OPTARG" ;;',
' n) count="$OPTARG" ;;',
' v) verbose=1 ;;',
' *) usage ;;',
' esac',
'done',
'[ -n "$file" ] || usage',
'[ "$verbose" -eq 1 ] && echo "reading $count lines from $file"',
'head -n "$count" "$file"')
)
@recipe("script","trap")
def s_trap_cleanup():
return (
"Write a script that creates a temp working directory and cleans it up on exit using a trap.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'workdir="$(mktemp -d)"',
'cleanup() { rm -rf "$workdir"; }',
"trap cleanup EXIT",
'echo "working in $workdir"',
'echo "some data" > "$workdir/data.txt"',
'wc -l "$workdir/data.txt"')
)
@recipe("script","case")
def s_case_service():
s = R(SERVICES)
return (
f"Write a start/stop/restart control script for the {s} service using a case statement.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'service={s}',
'case "${1:-}" in',
' start) sudo systemctl start "$service" ;;',
' stop) sudo systemctl stop "$service" ;;',
' restart) sudo systemctl restart "$service" ;;',
' status) systemctl status "$service" ;;',
' *) echo "usage: $0 {start|stop|restart|status}" >&2; exit 1 ;;',
'esac')
)
@recipe("script","tar")
def s_backup():
d = R(["/home/deploy","/var/www","/etc","/opt/app"])
return (
f"Write a backup script that tars {d} into a timestamped archive under /backup and keeps only the 7 newest.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'src={d}',
'dest=/backup',
'mkdir -p "$dest"',
'stamp=$(date +%Y%m%d-%H%M%S)',
'archive="$dest/backup-$stamp.tar.gz"',
'tar -czf "$archive" "$src"',
'echo "created $archive"',
'# retain only the 7 most recent backups',
'ls -1t "$dest"/backup-*.tar.gz | tail -n +8 | xargs -r rm -f')
)
@recipe("script","for")
def s_logrotate():
return (
"Write a simple log-rotation script that renames app.log to app.log.1..5 and truncates the current one.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'log=app.log',
'keep=5',
'for i in $(seq $keep -1 1); do',
' prev=$((i-1))',
' if [ "$prev" -eq 0 ]; then',
' [ -f "$log" ] && mv "$log" "$log.1"',
' else',
' [ -f "$log.$prev" ] && mv "$log.$prev" "$log.$i"',
' fi',
'done',
': > "$log"')
)
@recipe("script","retry")
def s_retry():
h = R(HOSTS)
return (
f"Write a script that retries a curl to https://{h}/health up to 5 times with a 2-second backoff.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'url=https://{h}/health',
'max=5',
'for attempt in $(seq 1 "$max"); do',
' if curl -fsS "$url" >/dev/null; then',
' echo "healthy on attempt $attempt"',
' exit 0',
' fi',
' echo "attempt $attempt failed, retrying..." >&2',
' sleep 2',
'done',
'echo "service never became healthy" >&2',
'exit 1')
)
@recipe("script","deploy")
def s_deploy():
b = R(BRANCHES)
return (
f"Write a deployment script: pull the {b} branch, install deps, run tests, and restart the service only if tests pass.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'branch={b}',
'echo "==> deploying $branch"',
'git fetch origin',
'git checkout "$branch"',
'git pull --ff-only origin "$branch"',
'npm ci',
'if npm test; then',
' sudo systemctl restart myapp',
' echo "deploy succeeded"',
'else',
' echo "tests failed, aborting deploy" >&2',
' exit 1',
'fi')
)
RECIPES[-1]["utility"]="git"
@recipe("script","heredoc")
def s_heredoc():
return (
"Write a script that generates an nginx config file for example.com using a here-document.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'domain=example.com',
'cat > "/etc/nginx/sites-available/$domain" <<EOF',
'server {',
' listen 80;',
' server_name $domain;',
' root /var/www/$domain;',
' location / {',
' try_files \\$uri \\$uri/ =404;',
' }',
'}',
'EOF',
'echo "wrote config for $domain"')
)
@recipe("script","function")
def s_arg_check():
return (
"Write a script that requires exactly two arguments (source and destination) and errors out otherwise.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'if [ "$#" -ne 2 ]; then',
' echo "usage: $0 SOURCE DEST" >&2',
' exit 1',
'fi',
'src="$1"',
'dest="$2"',
'[ -e "$src" ] || { echo "source $src does not exist" >&2; exit 1; }',
'cp -r -- "$src" "$dest"',
'echo "copied $src -> $dest"')
)
RECIPES[-1]["utility"]="args"
@recipe("script","while")
def s_countdown():
n = R([5,10,30])
return (
f"Write a countdown script from {n} to 1 that prints each number one second apart.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'i={n}',
'while [ "$i" -gt 0 ]; do',
' echo "$i"',
' sleep 1',
' i=$((i - 1))',
'done',
'echo "liftoff"')
)
@recipe("script","find")
def s_find_clean():
d = R(["/tmp","/var/log","logs","cache"])
days = R(DAYS)
return (
f"Write a script that deletes files older than {days} days from {d}, logging each removal.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'target={d}',
f'age={days}',
'find "$target" -type f -mtime +"$age" -print -delete | while IFS= read -r f; do',
' echo "$(date \'+%F %T\') removed $f"',
'done >> cleanup.log')
)
RECIPES[-1]["utility"]="find"
@recipe("script","function")
def s_menu():
return (
"Write an interactive menu script using select that lets the user pick disk, memory or uptime info.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'PS3="Choose an option: "',
'select opt in disk memory uptime quit; do',
' case "$opt" in',
' disk) df -h ;;',
' memory) free -h ;;',
' uptime) uptime -p ;;',
' quit) break ;;',
' *) echo "invalid choice" ;;',
' esac',
'done')
)
RECIPES[-1]["utility"]="select"
@recipe("script","if")
def s_check_root():
return (
"Write a script that refuses to run unless it's executed as root.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'if [ "$(id -u)" -ne 0 ]; then',
' echo "this script must be run as root" >&2',
' exit 1',
'fi',
'echo "running with root privileges"')
)
@recipe("script","for")
def s_mysql_backup():
return (
"Write a script that dumps every MySQL database into its own gzip file under /backup/db.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'dest=/backup/db',
'mkdir -p "$dest"',
'stamp=$(date +%F)',
'dbs=$(mysql -N -e "SHOW DATABASES" | grep -Ev "^(information_schema|performance_schema|mysql|sys)$")',
'for db in $dbs; do',
' mysqldump --single-transaction "$db" | gzip > "$dest/${db}-${stamp}.sql.gz"',
' echo "dumped $db"',
'done')
)
RECIPES[-1]["utility"]="mysqldump"
@recipe("script","trap")
def s_lockfile():
return (
"Write a script that uses a lock file so only one instance can run at a time, releasing it on exit.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'lock=/tmp/myjob.lock',
'if [ -e "$lock" ]; then',
' echo "another instance is already running" >&2',
' exit 1',
'fi',
'touch "$lock"',
'trap \'rm -f "$lock"\' EXIT',
'echo "doing work..."',
'sleep 2',
'echo "done"')
)
@recipe("script","while")
def s_watch_dir():
d = R(SDIRS)
return (
f"Write a script that watches {d} and prints a message whenever the file count changes.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'dir={d}',
'prev=$(ls -1 "$dir" | wc -l)',
'while true; do',
' sleep 5',
' cur=$(ls -1 "$dir" | wc -l)',
' if [ "$cur" -ne "$prev" ]; then',
' echo "$(date \'+%T\'): count changed $prev -> $cur"',
' prev=$cur',
' fi',
'done')
)
@recipe("script","function")
def s_require_cmds():
return (
"Write a script that checks a list of required commands (git, curl, jq) are installed before continuing.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'require() {',
' for cmd in "$@"; do',
' if ! command -v "$cmd" >/dev/null 2>&1; then',
' echo "missing required command: $cmd" >&2',
' exit 1',
' fi',
' done',
'}',
'require git curl jq',
'echo "all dependencies present"')
)
RECIPES[-1]["utility"]="command"
@recipe("script","for")
def s_batch_convert():
return (
"Write a script that converts every .png in the current directory to .jpg using ImageMagick, keeping originals.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
'shopt -s nullglob',
'for img in *.png; do',
' out="${img%.png}.jpg"',
' convert "$img" "$out"',
' echo "converted $img -> $out"',
'done')
)
@recipe("script","if")
def s_process_check():
p = R(PROCS)
return (
f"Write a script that checks whether {p} is running and starts it if not.",
L("#!/usr/bin/env bash",
"set -euo pipefail",
f'proc={p}',
'if pgrep -x "$proc" >/dev/null; then',
' echo "$proc is already running"',
'else',
' echo "$proc not running, starting it"',
' sudo systemctl start "$proc"',
'fi')
)
# ---- high-capacity idiomatic families for info/system utilities -----------
def _F(forms):
b, phr = random.choice(forms)
return random.choice(phr), b
@recipe("single","vmstat")
def r_vmstat2():
iv=R([1,2,3,5,10]); c=R([3,5,10,20,30])
nl,b=_F([
(f"vmstat {iv} {c}", (f"Report virtual-memory statistics every {iv} seconds, {c} times.",
f"Sample vmstat {c} times at a {iv}-second interval.",
f"Run vmstat every {iv}s and stop after {c} samples.",
f"give me {c} vmstat readings spaced {iv} seconds apart")),
(f"vmstat -S M {iv} {c}", (f"Show vmstat in megabytes, {iv}s interval, {c} samples.",
f"Run vmstat with MB units every {iv} seconds for {c} rounds.")),
(f"vmstat -a {iv}", (f"Watch active/inactive memory with vmstat every {iv}s.",
f"Show active vs inactive memory using vmstat at {iv}-second intervals.")),
(f"vmstat -w {iv} {c}", (f"Wide-format vmstat every {iv}s, {c} samples.",
f"Use vmstat's wide output, {iv}s apart, {c} times.")),
(f"vmstat -t {iv} {c}", (f"Timestamped vmstat every {iv}s for {c} samples.",
f"Add a timestamp column to vmstat, {iv}s interval, {c} rounds.")),
("vmstat", ("Show a single virtual-memory snapshot.","Print current vmstat counters once.",
"Give me a one-off vmstat summary.")),
("vmstat -s", ("Dump the vmstat table of memory and event counters.",
"Show the full 'vmstat -s' statistics.","Print vmstat's summary-of-events table.")),
("vmstat -d", ("Show per-disk statistics with vmstat.","Report disk I/O counters via vmstat -d.")),
("vmstat -s -S M", ("Show vmstat memory counters in megabytes.",
"Dump vmstat -s statistics using MB units.")),
])
return nl, b, "vmstat"
@recipe("single","iostat")
def r_iostat2():
iv=R([1,2,3,5,10]); c=R([3,5,10,20])
nl,b=_F([
(f"iostat {iv} {c}", (f"Show CPU and disk I/O stats every {iv} seconds, {c} times.",
f"Sample iostat {c} times at {iv}-second intervals.",
f"Run iostat every {iv}s for {c} reports.")),
(f"iostat -x {iv} {c}", (f"Extended disk I/O stats every {iv}s, {c} samples.",
f"Show detailed per-device iostat, {iv}s apart, {c} times.")),
(f"iostat -xz {iv}", (f"Extended iostat every {iv}s, hiding idle devices.",
f"Run iostat -x every {iv} seconds and skip zero-activity devices.")),
(f"iostat -d {iv}", (f"Device-only I/O stats every {iv} seconds.",
f"Show just disk stats with iostat every {iv}s.")),
(f"iostat -m {iv} {c}", (f"I/O stats in MB/s every {iv}s for {c} samples.",
f"Report iostat throughput in megabytes, {iv}s interval, {c} rounds.")),
("iostat -c", ("Show only the CPU utilization part of iostat.","Report CPU stats via iostat -c.")),
("iostat -xh", ("Show extended I/O stats in human-readable form.",
"Give me iostat -x with human-readable units.")),
("iostat", ("Show a one-shot CPU and disk I/O summary.","Print current iostat counters once.")),
(f"iostat -p sda {iv}", (f"Show per-partition stats for sda every {iv}s.",
f"Monitor the sda device and its partitions with iostat every {iv} seconds.")),
])
return nl, b, "iostat"
@recipe("single","free")
def r_free2():
iv=R([1,2,3,5]); c=R([3,5,10])
nl,b=_F([
("free -h", ("Show memory usage in human-readable units.","How much RAM is free right now?",
"Display current memory usage nicely formatted.","give me a human-readable memory summary")),
("free -m", ("Show memory usage in megabytes.","Report free and used memory in MB.")),
("free -g", ("Show memory usage in gigabytes.","Display RAM usage rounded to GB.")),
("free -b", ("Show memory usage in bytes.","Report memory in raw bytes.")),
("free -h -t", ("Show memory usage with a total line for RAM plus swap.",
"Include a combined RAM+swap total in the free output.")),
("free -w", ("Show memory usage with buffers and cache in separate columns.",
"Give me the wide free output splitting buffers and cache.")),
(f"free -h -s {iv}", (f"Refresh memory usage every {iv} seconds.",
f"Watch memory continuously, updating every {iv}s.")),
(f"free -m -s {iv} -c {c}", (f"Poll memory in MB every {iv}s, {c} times.",
f"Sample free {c} times at {iv}-second intervals in megabytes.")),
("free -l", ("Show low and high memory statistics with free.","Display free's low/high memory breakdown.")),
("free -h --si", ("Show memory usage using powers of 1000 (SI units).",
"Report memory in human-readable SI units.")),
])
return nl, b, "free"
@recipe("single","uptime")
def r_uptime2():
nl,b=_F([
("uptime", ("How long has the system been up?","Show uptime and load averages.",
"Print the current uptime line.","what's the load average and uptime?",
"Give me the one-line uptime summary.")),
("uptime -p", ("Show uptime in a human-friendly 'pretty' format.",
"How long has this box been running, in plain words?","Print uptime -p.",
"give me uptime in the pretty format")),
("uptime -s", ("When did the system last boot?","Show the exact boot timestamp.",
"Print the system's startup date and time.","what time did the machine come up?")),
("cat /proc/uptime", ("Show raw uptime in seconds from /proc.",
"Read the uptime directly out of /proc/uptime.")),
("awk '{print $1}' /proc/uptime", ("Print just the uptime in seconds.",
"Extract the number of seconds the system has been up.")),
("awk '{print int($1/86400)\" days\"}' /proc/uptime", ("Show the uptime rounded to whole days.",
"How many full days has the system been up?")),
("awk '{printf \"%d:%02d\\n\", $1/3600, ($1%3600)/60}' /proc/uptime", (
"Show uptime formatted as hours:minutes.","Print how long the system has been up in H:MM.")),
("uptime | awk -F'load average:' '{print $2}'", ("Show only the load averages.",
"Extract just the load-average part of uptime.")),
("uptime | grep -o 'load average.*'", ("Print only the load-average portion of uptime.",
"Grep out the load averages from the uptime line.")),
("uptime | cut -d, -f1", ("Show only the time portion of the uptime line.",
"Trim uptime down to just how long it's been up.")),
("cut -d' ' -f1 /proc/loadavg", ("Show the 1-minute load average.","Print the current 1-minute load.")),
("who -b", ("Show the last boot time using who.","When was the system booted, per who -b?")),
])
return nl, b, "uptime"
@recipe("single","w")
def r_w2():
u=R(USERS)
nl,b=_F([
("w", ("Show who is logged in and what they're doing.","List active users and their processes.",
"Who's on the system right now and running what?","Display the w summary of logged-in users.")),
("w -h", ("List logged-in users without the header line.","Show w output but skip the header.")),
("w -s", ("Show a short w listing without the login/JCPU/PCPU columns.",
"Give me the abbreviated w output.")),
("w -i", ("Show logged-in users with their IP addresses instead of hostnames.",
"Display w with numeric IPs.")),
("w -f", ("Show w output including the remote host each user came from.",
"Include the FROM field in the w listing.")),
(f"w {u}", (f"Show what user {u} is currently doing.",f"List {u}'s active sessions with w.",
f"What is {u} running right now?")),
(f"w -h {u}", (f"Show {u}'s sessions without the header.",f"List {u}'s activity, headerless.")),
(f"w -s {u}", (f"Short w listing for user {u}.",f"Abbreviated session info for {u}.")),
("w | wc -l", ("Count how many entries w reports.","How many active sessions are there per w?")),
("w -h | wc -l", ("Count the number of logged-in user sessions.",
"How many users are currently logged in?")),
])
return nl, b, "w"
@recipe("single","hostname")
def r_hostname2():
nl,b=_F([
("hostname", ("Print the system's hostname.","What is this machine's hostname?",
"Show the short hostname.")),
("hostname -I", ("Print all IP addresses assigned to this host.",
"What IPs does this machine have?","Show every local IP address, space separated.")),
("hostname -f", ("Show the fully qualified domain name.","What's the FQDN of this host?")),
("hostname -s", ("Show the short hostname (up to the first dot).","Print just the short hostname.")),
("hostname -d", ("Show the DNS domain name.","What domain is this host in?")),
("hostname -A", ("Show all FQDNs for this host.","List every fully-qualified name of the machine.")),
("hostname -i", ("Show the host's primary IP as resolved from its name.",
"Print the IP address hostname resolves to.")),
("hostname -I | awk '{print $1}'", ("Print only the primary (first) IP address.",
"Get just the first local IP address.")),
("uname -n", ("Show the network node hostname via uname.","Print the nodename with uname -n.")),
("cat /etc/hostname", ("Show the configured hostname from /etc/hostname.",
"Read the hostname straight from its config file.")),
])
return nl, b, "hostname"
@recipe("single","pstree")
def r_pstree2():
u=R(USERS); pid=random.randint(500,9000)
nl,b=_F([
("pstree -p", ("Show the process tree with PIDs.","Display the process hierarchy including PIDs.",
"Print pstree annotated with process IDs.")),
("pstree", ("Show the process tree.","Display all processes as a hierarchy.")),
("pstree -a", ("Show the process tree including command-line arguments.",
"Display pstree with each process's arguments.")),
("pstree -hp", ("Show the process tree with PIDs, highlighting the current process.",
"Print pstree highlighting the current branch, with PIDs.")),
("pstree -n", ("Show the process tree sorted numerically by PID.",
"Display pstree ordered by PID instead of by name.")),
("pstree -A", ("Show the process tree using ASCII line characters.",
"Print pstree with ASCII art instead of Unicode.")),
(f"pstree {u}", (f"Show the process tree for user {u}.",f"Display {u}'s processes as a tree.")),
(f"pstree -p {u}", (f"Show {u}'s process tree with PIDs.",f"Print {u}'s process hierarchy including PIDs.")),
(f"pstree -s {pid}", (f"Show the parent chain leading to PID {pid}.",
f"Display the ancestors of process {pid} as a tree.")),
(f"pstree -p {pid}", (f"Show the subtree of processes under PID {pid}.",
f"Display the children of process {pid}.")),
])
return nl, b, "pstree"
@recipe("single","dmesg")
def r_dmesg2():
pat=R(["usb","memory","error","sda","sdb","eth0","enp0s3","oom","segfault","firmware",
"tcp","cpu","disk","i/o","link","reset","timeout","nvme","kvm","thermal"])
n=R([10,20,30,50,100]); since=R(["10 min ago","1 hour ago","today","30 min ago","yesterday"])
fac=R(["kern","daemon","syslog","user"])
nl,b=_F([
("dmesg -T", ("Show kernel messages with human-readable timestamps.",
"Print the kernel ring buffer with real timestamps.","Display dmesg using -T timestamps.")),
("dmesg -w", ("Follow new kernel messages as they arrive.","Watch the kernel log live.")),
("dmesg -H", ("Show kernel messages in the pager with human-readable output.",
"Display dmesg in human-friendly mode.")),
("dmesg -l err,warn", ("Show only kernel error and warning messages.",
"Filter dmesg to errors and warnings.","Display kernel warnings and errors only.")),
("dmesg -l err", ("Show only kernel error-level messages.","Filter the kernel log to errors.")),
("dmesg -l warn", ("Show only kernel warning-level messages.","Filter dmesg to warnings.")),
("dmesg -l notice", ("Show kernel notice-level messages.","Filter the kernel log to notices.")),
("dmesg --level=crit", ("Show only critical kernel messages.","Filter dmesg to critical level.")),
("dmesg -x", ("Show kernel messages with facility and level decoded.",
"Print dmesg with the facility/level prefix.")),
("dmesg -t", ("Show kernel messages without the timestamp prefix.","Print dmesg with timestamps stripped.")),
("dmesg -r", ("Show the raw kernel message buffer.","Print dmesg in raw format with priority markers.")),
(f"dmesg -f {fac}", (f"Show kernel messages from the {fac} facility.",
f"Filter dmesg to the {fac} facility.")),
(f"dmesg -T --since '{since}'", (f"Show kernel messages since {since}.",
f"Print dmesg entries from {since} onward with timestamps.")),
(f"dmesg -T | tail -n {n}", (f"Show the last {n} kernel log lines with timestamps.",
f"Print the most recent {n} dmesg entries.")),
(f"dmesg -T | grep -i {pat}", (f"Search the kernel log for '{pat}' messages.",
f"Find any dmesg lines mentioning {pat}.",f"Grep the kernel ring buffer for {pat}.")),
(f"dmesg --level=err | grep -i {pat}", (f"Find kernel errors related to {pat}.",
f"Show error-level dmesg lines mentioning {pat}.")),
("dmesg -k", ("Show only kernel-generated messages.","Restrict dmesg to kernel messages.")),
])
return nl, b, "dmesg"
@recipe("single","netstat")
def r_netstat2():
port=R(PORTS); h=R(HOSTS)
nl,b=_F([
("netstat -tulpn", ("List all listening ports with the owning programs.",
"Show listening TCP/UDP sockets and their PIDs.","What's listening on this machine and on which ports?")),
("netstat -rn", ("Show the kernel routing table numerically.","Print the routing table without DNS lookups.")),
("netstat -i", ("Show network interface statistics.","Display per-interface counters.")),
("netstat -s", ("Show summary statistics for each protocol.","Print protocol-level network stats.")),
("netstat -an", ("Show all sockets numerically.","List every connection without resolving names.")),
("netstat -tn", ("Show established TCP connections numerically.","List active TCP sessions with numeric addresses.")),
("netstat -ltn", ("Show listening TCP ports numerically.","List TCP listeners without name resolution.")),
(f"netstat -anp | grep :{port}", (f"Show connections on port {port}.",
f"Find any socket using port {port} via netstat.")),
(f"netstat -tn | grep {h}", (f"Show TCP connections involving {h}.",
f"Filter netstat for connections to or from {h}.")),
("netstat -tunlp", ("List all listening TCP and UDP ports with programs.",
"Show every listening socket and its process.")),
])
return nl, b, "netstat"
@recipe("single","nice")
def r_nice2():
v=R([1,5,10,15,19,-5,-10]); c=random.randint(1000,9999)
cmd=R(["tar -czf backup.tar.gz /home/deploy","python train.py","make -j4","ffmpeg -i in.mp4 out.mp4",
"rsync -a /data /mnt/backup","gzip huge.log","./import.sh","npm run build",
"find / -name '*.core'","dd if=/dev/zero of=test.img bs=1M count=1024"])
if v < 0:
nl,b=_F([
(f"sudo nice -n {v} {cmd}", (f"Run '{cmd}' at higher priority (nice {v}); needs root.",
f"Give '{cmd}' a boosted CPU priority of {v}.")),
])
else:
nl,b=_F([
(f"nice -n {v} {cmd}", (f"Run '{cmd}' at a lower priority (nice {v}).",
f"Start '{cmd}' with nice value {v} so it doesn't hog the CPU.",
f"Launch '{cmd}' at reduced priority ({v}).")),
(f"nice -n {v} {cmd} &", (f"Run '{cmd}' niced to {v} in the background.",
f"Background '{cmd}' at nice level {v}.")),
])
return nl, b, "nice"
# ---- high-capacity parameterized PIPELINE families (dynamic utility labels) -
@recipe("pipeline","freqtop")
def p_freqtop():
f = R(LOGFILES + CSVFILES)
fld = R([1,2,3,4,5,7,9]); n = R([5,10,15,20,25])
sep, extract, util = R([
("whitespace-separated", f"awk '{{print ${fld}}}' {f}", "awk"),
("comma-separated", f"cut -d, -f{fld} {f}", "cut"),
])
nl = pick(
f"Show the top {n} most frequent values in field {fld} of the {sep} file {f}.",
f"What are the {n} most common entries in column {fld} of {f}?",
f"Rank the values of column {fld} in {f} by frequency, highest first, top {n} only.",
f"Give me a frequency tally of column {fld} in {f} and show the {n} biggest.",
f"In {f}, which {n} values of column {fld} occur most often?",
f"Count how often each column-{fld} value appears in {f}; show the {n} most common.",
f"From {f}, list the {n} most frequent field-{fld} entries with their counts.",
f"Tally column {fld} of {f} and print the {n} top values by count.",
f"Find the {n} hottest values in column {fld} of {f} (by frequency).",
)
return nl, f"{extract} | sort | uniq -c | sort -nr | head -n {n}", util
@recipe("pipeline","catpipe")
def p_catpipe():
f = R(TEXTFILES)
op, cmd, util = R([
("count the lines", "wc -l", "wc"),
("sort it and drop duplicate lines", "sort -u", "sort"),
("show the 20 longest lines", "awk '{ print length, $0 }' | sort -rn | head -20 | cut -d' ' -f2-", "awk"),
("convert everything to uppercase", "tr 'a-z' 'A-Z'", "tr"),
("show the last 15 lines", "tail -n 15", "tail"),
("keep only non-empty lines", "grep -v '^$'", "grep"),
("count each unique line, most common first", "sort | uniq -c | sort -nr", "uniq"),
("strip trailing whitespace", "sed 's/[[:space:]]*$//'", "sed"),
])
nl = pick(f"Take {f} and {op}.", f"From {f}, {op}.",
f"Read {f}, then {op} — as a pipeline.", f"Given {f}, {op}.")
return nl, f"cat {f} | {cmd}", util
@recipe("pipeline","procpipe")
def p_procpipe():
n = R([5,10,15]); p = R(PROCS)
variant, bash, util = R([
(f"show the top {n} processes by memory", f"ps aux --sort=-%mem | head -n {n+1}", "ps"),
(f"show the top {n} processes by CPU usage", f"ps aux --sort=-%cpu | head -n {n+1}", "ps"),
(f"total the resident memory of all {p} processes in MB", f"ps -C {p} -o rss= | awk '{{s+=$1}} END{{print s/1024 \" MB\"}}'", "ps"),
(f"count how many {p} processes are running", f"pgrep -c {p}", "pgrep"),
(f"list the PIDs of {p} sorted by memory use", f"ps -C {p} -o pid=,rss= --sort=-rss", "ps"),
])
nl = pick(f"Help me {variant}.", f"{variant[0].upper()+variant[1:]}.", f"How do I {variant}?")
return nl, bash, util
@recipe("pipeline","netpipe")
def p_netpipe():
n = R([5,10,20])
variant, bash, util = R([
("count established TCP connections", "ss -tn state established | tail -n +2 | wc -l", "ss"),
(f"list the top {n} remote IPs by number of connections", f"ss -tn | awk 'NR>1 {{print $5}}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -n {n}", "ss"),
("show which processes are listening and on which ports", "ss -tlnp | awk 'NR>1 {print $4, $6}'", "ss"),
(f"find the {n} processes with the most open files", f"lsof 2>/dev/null | awk '{{print $1}}' | sort | uniq -c | sort -nr | head -n {n}", "lsof"),
("count connections grouped by their TCP state", "ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr", "ss"),
])
nl = pick(f"On this box, {variant}.", f"I want to {variant}.", f"Write a one-liner to {variant}.")
return nl, bash, util
@recipe("pipeline","logscan")
def p_logscan():
s = R(SERVICES); f = R(LOGFILES); p = R(PATTERNS); n = R([10,20,50])
variant, bash, util = R([
(f"count '{p}' occurrences in the {s} journal today", f"journalctl -u {s} --since today --no-pager | grep -c '{p}'", "journalctl"),
(f"show the last {n} lines containing '{p}' in {f}", f"grep '{p}' {f} | tail -n {n}", "grep"),
(f"tally how many times each log level appears in {f}", f"grep -oE '(INFO|WARN|ERROR|DEBUG)' {f} | sort | uniq -c | sort -nr", "grep"),
(f"list the unique '{p}' messages in {f}", f"grep '{p}' {f} | sort -u", "grep"),
(f"follow the {s} journal but only show lines mentioning '{p}'", f"journalctl -u {s} -f | grep --line-buffered -i '{p}'", "journalctl"),
])
nl = pick(f"I need to {variant}.", f"{variant[0].upper()+variant[1:]}.", f"Show me how to {variant}.")
return nl, bash, util
@recipe("pipeline","diskpipe")
def p_diskpipe():
d = R(DIRS); n = R([5,10,20])
variant, bash, util = R([
(f"the {n} biggest files under {d}", f"find {d} -type f -printf '%s %p\\n' 2>/dev/null | sort -rn | head -n {n}", "find"),
(f"the {n} largest subdirectories of {d}", f"du -h {d}/* 2>/dev/null | sort -rh | head -n {n}", "du"),
("how full each mounted filesystem is, worst first", "df -h | awk 'NR>1 {print $5, $6}' | sort -rn", "df"),
(f"the disk usage of {d} broken down one level deep", f"du -h --max-depth=1 {d} 2>/dev/null | sort -rh", "du"),
])
nl = pick(f"Show me {variant}.", f"What are {variant}?", f"List {variant}.")
return nl, bash, util
@recipe("single","fileq")
def r_fileq():
f = R(FILES)
variant, bash, util = R([
("show the first 20 lines", f"head -n 20 {f}", "head"),
("show the last 20 lines", f"tail -n 20 {f}", "tail"),
("count the lines", f"wc -l {f}", "wc"),
("print it with line numbers", f"nl {f}", "nl"),
("show its size, owner and permissions", f"stat {f}", "stat"),
("determine what kind of file it is", f"file {f}", "file"),
("show just the first line", f"head -n 1 {f}", "head"),
("show a hex dump of the first 64 bytes", f"xxd -l 64 {f}", "xxd"),
])
nl = pick(f"For {f}, {variant}.", f"{variant[0].upper()+variant[1:]} of {f}.",
f"Please {variant} in {f}.", f"On the file {f}, {variant}.")
return nl, bash, util
# ---- high-capacity parameterized script families (dynamic utility labels) --
WORKDIRS = ["/home/deploy","/var/www","/opt/app","/srv/data","/home/alice",
"/var/lib/app","/data/uploads","/mnt/storage","logs","data","backups"]
BACKDESTS = ["/backup","/mnt/backup","/var/backups","/srv/backup","/data/backup"]
KEEPS = [3,5,7,10,14,30]
THRESH = [70,75,80,85,90,95]
_FILE_ACTIONS = [
("compresses each file with gzip", 'gzip -- "$f"', "gzip"),
("removes each matching file", 'rm -f -- "$f"', "rm"),
("makes each file read-only", 'chmod 444 -- "$f"', "chmod"),
("makes a .bak copy of each file", 'cp -- "$f" "$f.bak"', "cp"),
("prints the line count of each file", 'wc -l -- "$f"', "wc"),
("moves each file into an archive/ subfolder", 'mv -- "$f" archive/', "mv"),
("changes the owner of each file to deploy", 'chown deploy -- "$f"', "chown"),
]
@recipe("script","fileproc")
def s_fileproc():
d = R(WORKDIRS); e = R(EXTS); desc, act, util = R(_FILE_ACTIONS)
nl = pick(
f"Write a script that loops over every .{e} file in {d} and {desc}.",
f"I need a bash script that {desc} for all .{e} files under {d}.",
f"Loop through the .{e} files in {d} and {desc} — write it as a proper script.",
f"Give me a script that iterates over {d}/*.{e} and {desc}.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'dir={d}',
f'for f in "$dir"/*.{e}; do',
' [ -e "$f" ] || continue',
f' {act}',
' echo "processed $f"',
'done')
return nl, body, util
_RES_MON = [
("root filesystem usage", "df / | awk 'NR==2 {print $5}' | tr -d '%'", "disk usage"),
("memory usage", "free | awk '/Mem/ {printf \"%d\", $3/$2*100}'", "memory usage"),
("the /home partition usage", "df /home | awk 'NR==2 {print $5}' | tr -d '%'", "/home usage"),
("swap usage", "free | awk '/Swap/ {if($2>0) printf \"%d\", $3/$2*100; else print 0}'", "swap usage"),
]
@recipe("script","monitor")
def s_monitor():
label, expr, human = R(_RES_MON); th = R(THRESH)
util = "df" if "df" in expr else "free"
nl = pick(
f"Write a monitoring script that warns when {label} exceeds {th}%.",
f"Alert me (exit non-zero) if {label} goes above {th} percent.",
f"I want a script checking {label}; if it's over {th}% print a warning to stderr.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'threshold={th}',
f'usage=$({expr})',
'if [ "$usage" -gt "$threshold" ]; then',
f' echo "ALERT: {human} is at ${{usage}}% (limit ${{threshold}}%)" >&2',
' exit 1',
'fi',
f'echo "{human} OK at ${{usage}}%"')
return nl, body, util
@recipe("script","backup2")
def s_backup2():
src = R(WORKDIRS); dest = R(BACKDESTS); keep = R(KEEPS)
comp, flag, ext = R([("gzip","z","gz"),("bzip2","j","bz2"),("xz","J","xz")])
nl = pick(
f"Write a backup script that {comp}-compresses {src} into a timestamped tarball under {dest} and keeps only the {keep} newest.",
f"Back up {src} to {dest} as a dated {comp} archive, pruning all but the last {keep} backups.",
f"I need a rotating backup: archive {src} into {dest} with {comp}, retain {keep} copies.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'src={src}',
f'dest={dest}',
f'keep={keep}',
'mkdir -p "$dest"',
'stamp=$(date +%Y%m%d-%H%M%S)',
f'archive="$dest/$(basename "$src")-$stamp.tar.{ext}"',
f'tar -c{flag}f "$archive" "$src"',
'echo "created $archive"',
'ls -1t "$dest"/*.tar.* | tail -n +$((keep + 1)) | xargs -r rm -f')
return nl, body, "tar"
@recipe("script","hosts")
def s_hosts_iter():
f = R(["hosts.txt","servers.txt","nodes.txt","targets.txt"])
action, cmd, util = R([
("pings each host once", 'ping -c1 -W1 "$host" >/dev/null 2>&1', "ping"),
("checks if port 22 is open", 'timeout 2 bash -c "echo > /dev/tcp/$host/22" 2>/dev/null', "ssh"),
("curls the /health endpoint", 'curl -fsS "http://$host/health" >/dev/null', "curl"),
])
nl = pick(
f"Read {f} and for each host, report UP/DOWN based on whether it {action}.",
f"Write a health-check loop over {f} that {action} and prints the status of each.",
f"Iterate the hosts in {f}; the script {action} and marks each reachable or not.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
'while IFS= read -r host; do',
' [ -z "$host" ] && continue',
' case "$host" in \\#*) continue ;; esac',
f' if {cmd}; then',
' echo "$host UP"',
' else',
' echo "$host DOWN"',
' fi',
f'done < {f}')
return nl, body, util
@recipe("script","getopts2")
def s_getopts2():
a,b,c = random.sample(["input","output","count","name","dir","level","port","tag"],3)
fa,fb,fc = a[0], b[0], c[0]
nl = pick(
f"Write a script that accepts --{a} (-{fa}), --{b} (-{fb}) and --{c} (-{fc}) via getopts, with a usage message.",
f"Parse command-line flags -{fa} ({a}), -{fb} ({b}) and -{fc} ({c}) using getopts and validate that -{fa} is provided.",
f"I need getopts handling for three options: -{fa}, -{fb} and -{fc}; print usage on bad input.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'{a}=""; {b}=""; {c}=""',
f'usage() {{ echo "usage: $0 -{fa} {a.upper()} [-{fb} {b.upper()}] [-{fc} {c.upper()}]" >&2; exit 1; }}',
f'while getopts ":{fa}:{fb}:{fc}:" opt; do',
' case "$opt" in',
f' {fa}) {a}="$OPTARG" ;;',
f' {fb}) {b}="$OPTARG" ;;',
f' {fc}) {c}="$OPTARG" ;;',
' *) usage ;;',
' esac',
'done',
f'[ -n "${{{a}}}" ] || usage',
f'echo "{a}=${{{a}}} {b}=${{{b}}} {c}=${{{c}}}"')
return nl, body, "getopts"
@recipe("script","retry2")
def s_retry2():
h = R(HOSTS); mx = R([3,4,5,6,10]); sl = R([1,2,3,5])
thing, cmd, util = R([
("curl to https://%s/health" % h, f'curl -fsS "https://{h}/health" >/dev/null', "curl"),
("connection to %s:5432" % h, f'timeout 2 bash -c "echo > /dev/tcp/{h}/5432"', "bash"),
("git fetch from origin", 'git fetch origin', "git"),
])
nl = pick(
f"Write a script that retries a {thing} up to {mx} times, sleeping {sl}s between attempts.",
f"Retry {thing} at most {mx} times with a {sl}-second backoff, failing loudly if it never succeeds.",
f"I need a retry wrapper around {thing}: {mx} attempts, {sl}s apart.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'max={mx}',
f'delay={sl}',
'for attempt in $(seq 1 "$max"); do',
f' if {cmd}; then',
' echo "succeeded on attempt $attempt"',
' exit 0',
' fi',
' echo "attempt $attempt failed" >&2',
' sleep "$delay"',
'done',
'echo "giving up after $max attempts" >&2',
'exit 1')
return nl, body, util
@recipe("script","findclean2")
def s_findclean2():
d = R(["/tmp","/var/log","/var/cache","logs","cache","uploads","/var/tmp"])
days = R(DAYS); e = R(["log","tmp","bak","gz","old","cache"])
nl = pick(
f"Write a script that deletes .{e} files older than {days} days from {d} and logs what it removed.",
f"Clean up {d}: remove .{e} files not modified in {days} days, recording each deletion.",
f"I want a cleanup script for {d} that purges .{e} files older than {days} days.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'target={d}',
f'age={days}',
'[ -d "$target" ] || { echo "no such dir: $target" >&2; exit 1; }',
f'find "$target" -type f -name "*.{e}" -mtime +"$age" -print -delete \\',
' | sed "s/^/removed /" | tee -a cleanup.log')
return nl, body, "find"
@recipe("script","funcs2")
def s_funcs2():
lv = R(["INFO","DEBUG","NOTICE"])
nl = pick(
"Write a script with a die() helper that logs an error to stderr and exits, plus a log() helper for info messages.",
"I want reusable log() and die() shell functions with timestamps; die should exit 1.",
"Give me a small bash logging library: log() writes info, die() writes an error and aborts.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
"ts() { date '+%Y-%m-%d %H:%M:%S'; }",
f'log() {{ printf \'%s [{lv}] %s\\n\' "$(ts)" "$*"; }}',
'die() { printf \'%s [ERROR] %s\\n\' "$(ts)" "$*" >&2; exit 1; }',
'log "starting"',
'[ -f config.yaml ] || die "config.yaml is missing"',
'log "config found, continuing"')
return nl, body, "function"
@recipe("script","dbdump")
def s_dbdump():
dest = R(BACKDESTS); keep = R(KEEPS)
engine, listcmd, dumpcmd, util = R([
("MySQL", 'mysql -N -e "SHOW DATABASES"', "mysqldump --single-transaction", "mysqldump"),
("PostgreSQL", "psql -tAc 'SELECT datname FROM pg_database WHERE NOT datistemplate'", "pg_dump", "pg_dump"),
])
nl = pick(
f"Write a script that dumps every {engine} database into its own gzip file under {dest}, keeping {keep} days.",
f"Back up all {engine} databases individually to {dest} as compressed dumps.",
f"I need per-database {engine} backups written to {dest} and pruned after {keep} days.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'dest={dest}',
f'keep={keep}',
'mkdir -p "$dest"',
'stamp=$(date +%F)',
f'for db in $({listcmd}); do',
f' {dumpcmd} "$db" | gzip > "$dest/${{db}}-${{stamp}}.sql.gz"',
' echo "dumped $db"',
'done',
'find "$dest" -name "*.sql.gz" -mtime +"$keep" -delete')
return nl, body, util
@recipe("script","parallel")
def s_parallel():
d = R(WORKDIRS); e = R(EXTS); n = R([2,4,8])
tool, cmd, util = R([
("gzip", 'gzip', "gzip"),
("checksum with sha256sum", 'sha256sum', "sha256sum"),
("optipng", 'optipng', "optipng"),
])
nl = pick(
f"Write a script that runs {tool} on every .{e} file in {d}, {n} jobs in parallel.",
f"Process all .{e} files under {d} with {tool} using {n} parallel workers via xargs.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'dir={d}',
f'find "$dir" -type f -name "*.{e}" -print0 \\',
f' | xargs -0 -P {n} -n1 {cmd}',
'echo "done"')
return nl, body, "xargs"
@recipe("script","envcheck")
def s_envcheck():
v1,v2,v3 = random.sample(["API_KEY","DB_HOST","DB_PASS","AWS_REGION","REDIS_URL","PORT","ENV"],3)
nl = pick(
f"Write a script that verifies the environment variables {v1}, {v2} and {v3} are all set before running.",
f"Fail fast if any of {v1}, {v2}, {v3} is unset — write it as a bash guard.",
f"I need a preflight check that {v1}, {v2} and {v3} exist in the environment.",
)
body = L("#!/usr/bin/env bash",
"set -euo pipefail",
f'for var in {v1} {v2} {v3}; do',
' if [ -z "${!var:-}" ]; then',
' echo "required environment variable $var is not set" >&2',
' exit 1',
' fi',
'done',
'echo "environment looks good"')
return nl, body, "env"
@recipe("script","for")
def s_for_big():
kind = random.randint(0,4)
if kind == 0:
base = R(BACKDESTS); n = R([3,5,7,14,30])
nl = pick(f"Write a script that pre-creates dated subdirectories under {base} for the next {n} days.",
f"Make {n} day-stamped folders under {base} using a for loop over a date range.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'base={base}',
f'for i in $(seq 0 {n-1}); do',
' day=$(date -d "+$i day" +%Y-%m-%d)',
' mkdir -p "$base/$day"',
' echo "created $base/$day"','done')
return nl, body, "for"
if kind == 1:
d = R(WORKDIRS); e = R(EXTS)
nl = pick(f"Loop over every .{e} file in {d} and append its sha256 checksum to checksums.txt.",
f"For each .{e} file under {d}, record a sha256 checksum in a manifest file.")
body = L("#!/usr/bin/env bash","set -euo pipefail","shopt -s nullglob",
f'for f in {d}/*.{e}; do',
' sha256sum "$f" >> checksums.txt',
'done',
'echo "wrote $(wc -l < checksums.txt) checksums"')
return nl, body, "for"
if kind == 2:
svcs = " ".join(random.sample(SERVICES, 3))
nl = pick(f"Write a loop that restarts these services in order: {svcs}.",
f"Restart {svcs} one after another and report each result.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
f'for svc in {svcs}; do',
' if sudo systemctl restart "$svc"; then',
' echo "$svc restarted"',
' else',
' echo "failed to restart $svc" >&2',
' fi','done')
return nl, body, "for"
if kind == 3:
d = R(WORKDIRS)
nl = pick(f"Loop over all subdirectories of {d} and print each one's total size.",
f"For every immediate subdirectory of {d}, show how much disk it uses.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
f'for dir in {d}/*/; do',
' [ -d "$dir" ] || continue',
' size=$(du -sh "$dir" | cut -f1)',
' printf "%-40s %s\\n" "$dir" "$size"','done')
return nl, body, "for"
prefix = R(["img","photo","scan","doc","page","frame"]); e = R(["jpg","png","txt","pdf"])
nl = pick(f"Rename all .{e} files in the current folder to {prefix}_001.{e}, {prefix}_002.{e}, ... sequentially.",
f"Batch-number every .{e} file as {prefix}_NNN.{e} using a counter in a for loop.")
body = L("#!/usr/bin/env bash","set -euo pipefail","shopt -s nullglob","i=1",
f'for f in *.{e}; do',
f' printf -v newname "{prefix}_%03d.{e}" "$i"',
' mv -- "$f" "$newname"',
' i=$((i + 1))','done')
return nl, body, "for"
@recipe("script","while")
def s_while_big():
kind = random.randint(0,3)
if kind == 0:
f = R(["hosts.txt","servers.txt","urls.txt","targets.txt","nodes.txt"])
nl = pick(f"Read {f} line by line, skipping comments and blanks, and echo each entry numbered.",
f"Process {f} one line at a time, ignoring # comments, printing a running index.")
body = L("#!/usr/bin/env bash","set -euo pipefail","n=0",
'while IFS= read -r line; do',
' [ -z "$line" ] && continue',
' case "$line" in \\#*) continue ;; esac',
' n=$((n + 1))',
' printf "%3d: %s\\n" "$n" "$line"',
f'done < {f}')
return nl, body, "while"
if kind == 1:
c = R(CSVFILES)
nl = pick(f"Read the CSV {c} field by field (id,name,email) with a while loop and print a greeting.",
f"Parse {c} as comma-separated id,name,email using while read and print each name.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
f'while IFS=, read -r id name email; do',
' [ "$id" = "id" ] && continue',
' echo "Hello $name <$email> (#$id)"',
f'done < {c}')
return nl, body, "while"
if kind == 2:
th = R(THRESH)
nl = pick(f"Write a watchdog loop that checks every 10s and only alerts once when disk passes {th}%.",
f"Poll disk usage every 10 seconds; warn a single time when it first exceeds {th}%.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'limit={th}',"alerted=0",
'while true; do',
" usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')",
' if [ "$usage" -ge "$limit" ] && [ "$alerted" -eq 0 ]; then',
' echo "disk crossed ${limit}% (now ${usage}%)" >&2',
' alerted=1',
' fi',
' sleep 10','done')
return nl, body, "while"
n = R([10,20,50,100])
nl = pick(f"Use a while loop to print the numbers 1 to {n}, but only the even ones.",
f"Print even numbers up to {n} with a while loop and a counter.")
body = L("#!/usr/bin/env bash","set -euo pipefail","i=2",f'max={n}',
'while [ "$i" -le "$max" ]; do',
' echo "$i"',
' i=$((i + 2))','done')
return nl, body, "while"
@recipe("script","if")
def s_if_big():
kind = random.randint(0,3)
if kind == 0:
f = R(FILES)
nl = pick(f"Write a script that checks whether {f} exists and is non-empty, printing an appropriate message.",
f"Test if {f} is present and has content; report missing, empty, or its line count.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'file={f}',
'if [ ! -e "$file" ]; then',
' echo "$file does not exist" >&2; exit 1',
'elif [ ! -s "$file" ]; then',
' echo "$file exists but is empty"',
'else',
' echo "$file has $(wc -l < "$file") lines"',
'fi')
return nl, body, "if"
if kind == 1:
p = R(PROCS)
nl = pick(f"Check whether {p} is running and exit 0 if so, 1 otherwise, with a message.",
f"Write a health check that reports UP/DOWN for the {p} process via its exit code.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'proc={p}',
'if pgrep -x "$proc" >/dev/null 2>&1; then',
' echo "$proc is running"; exit 0',
'else',
' echo "$proc is NOT running" >&2; exit 1',
'fi')
return nl, body, "if"
if kind == 2:
nl = pick("Write a script that verifies it is run with at least one argument, else prints usage.",
"Guard a script so it requires one or more arguments and shows usage otherwise.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
'if [ "$#" -lt 1 ]; then',
' echo "usage: $0 ARG [ARG...]" >&2',
' exit 2',
'fi',
'echo "got $# argument(s): $*"')
return nl, body, "if"
h = R(HOSTS)
nl = pick(f"Ping {h} once and branch: print reachable or unreachable based on the result.",
f"Write an if that checks connectivity to {h} with a single ping.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'host={h}',
'if ping -c1 -W2 "$host" >/dev/null 2>&1; then',
' echo "$host is reachable"',
'else',
' echo "$host is unreachable" >&2',
'fi')
return nl, body, "if"
@recipe("script","case")
def s_case_big():
kind = random.randint(0,2)
if kind == 0:
s = R(SERVICES)
nl = pick(f"Write a start/stop/restart/status control script for {s} using a case statement.",
f"Give me an init-style dispatcher for the {s} service with case on $1.")
body = L("#!/usr/bin/env bash","set -euo pipefail",f'svc={s}',
'case "${1:-}" in',
' start) sudo systemctl start "$svc" ;;',
' stop) sudo systemctl stop "$svc" ;;',
' restart) sudo systemctl restart "$svc" ;;',
' status) systemctl status "$svc" ;;',
' *) echo "usage: $0 {start|stop|restart|status}" >&2; exit 1 ;;',
'esac')
return nl, body, "case"
if kind == 1:
e = R(["jpg","png","gif","pdf","txt","log","tar.gz","zip","mp4","csv"])
nl = pick(f"Write a script that categorizes a filename by extension using case (is a .{e} an image, archive, doc?).",
"Classify a file passed as $1 into image/archive/document/other with a case on its extension.")
body = L("#!/usr/bin/env bash","set -euo pipefail",'file="${1:?usage: $0 FILE}"',
'case "$file" in',
' *.jpg|*.png|*.gif) echo "image" ;;',
' *.tar.gz|*.zip|*.gz) echo "archive" ;;',
' *.pdf|*.txt|*.md) echo "document" ;;',
' *) echo "other" ;;',
'esac')
return nl, body, "case"
nl = pick("Write a script that reads a yes/no answer and handles Y/y/yes and N/n/no with a case statement.",
"Handle a confirmation prompt: accept yes/no in any capitalization using case.")
body = L("#!/usr/bin/env bash","set -euo pipefail",'answer="${1:-no}"',
'case "${answer,,}" in',
' y|yes) echo "proceeding" ;;',
' n|no) echo "aborting"; exit 1 ;;',
' *) echo "please answer yes or no" >&2; exit 2 ;;',
'esac')
return nl, body, "case"
@recipe("script","function")
def s_func_big():
kind = random.randint(0,2)
if kind == 0:
nl = pick("Write a script with a confirm() function that asks the user to confirm before a destructive action.",
"Give me a reusable confirm() helper that returns success only on an explicit yes.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
'confirm() {',
' read -r -p "${1:-Are you sure?} [y/N] " reply',
' case "${reply,,}" in y|yes) return 0 ;; *) return 1 ;; esac',
'}',
'if confirm "Delete all temp files?"; then',
' echo "deleting..."',
'else',
' echo "cancelled"',
'fi')
return nl, body, "function"
if kind == 1:
n = R([3,4,5])
nl = pick(f"Write a retry() function that runs any command up to {n} times until it succeeds.",
f"Give me a generic retry wrapper function (max {n} tries) I can call with any command.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
'retry() {',
f' local max={n} i=1',
' until "$@"; do',
' if [ "$i" -ge "$max" ]; then',
' echo "command failed after $max attempts: $*" >&2',
' return 1',
' fi',
' i=$((i + 1)); sleep 1',
' done',
'}',
'retry curl -fsS https://api.example.com/health')
return nl, body, "function"
nl = pick("Write a script defining a human-readable size formatter function and use it on a file.",
"Give me a bytes-to-human function and demonstrate it on a file's size.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
'human() {',
' local b=$1 units=(B K M G T) i=0',
' while [ "$b" -ge 1024 ] && [ "$i" -lt 4 ]; do',
' b=$((b / 1024)); i=$((i + 1))',
' done',
' echo "${b}${units[$i]}"',
'}',
'human "$(stat -c %s "${1:-/etc/hostname}")"')
return nl, body, "function"
@recipe("script","report")
def s_report_big():
d = R(WORKDIRS); e = R(EXTS)
nl = pick(f"Write a script that prints a small system report: hostname, uptime, disk and memory usage.",
f"Generate a status summary showing host, load, free memory and root disk usage.",
f"I want a one-shot health report script covering uptime, memory and disk.")
body = L("#!/usr/bin/env bash","set -euo pipefail",
"mem=$(free -h | awk '/Mem/ {print $3\"/\"$2}')",
"disk=$(df -h / | awk 'NR==2 {print $3\"/\"$2\" (\"$5\")\"}')",
"load=$(cut -d' ' -f1-3 /proc/loadavg)",
'echo "===== system report ====="',
'echo "host: $(hostname)"',
'echo "uptime: $(uptime -p)"',
'echo "load: $load"',
'echo "memory: $mem"',
'echo "disk: $disk"')
return nl, body, "report"
# --------------------------------------------------------------------------
# engine
# --------------------------------------------------------------------------
def load_state():
counts_cat = {"single":0,"pipeline":0,"script":0}
counts_util = {}
seen = set()
total = 0
if os.path.exists(OUT):
with open(OUT, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
o = json.loads(line)
except json.JSONDecodeError:
continue
nl, bash = row_nl_bash(o)
total += 1
counts_cat[o["category"]] = counts_cat.get(o["category"],0)+1
counts_util[o["utility"]] = counts_util.get(o["utility"],0)+1
h = hashlib.sha1((nl+"\x00"+bash).encode()).hexdigest()
seen.add(h)
return {"total":total,"cat":counts_cat,"util":counts_util,"seen":seen}
def row_nl_bash(o):
"""Extract (nl, bash) from a dataset row in either schema."""
if "messages" in o:
nl = next(m["content"] for m in o["messages"] if m["role"] == "user")
bash = next(m["content"] for m in o["messages"] if m["role"] == "assistant")
return nl, bash
return o["nl"], o["bash"]
def save_progress(state):
snap = {
"total": state["total"],
"target_total": TARGET_TOTAL,
"category_target": CAT_TARGET,
"category_counts": state["cat"],
"util_cap": UTIL_CAP,
"util_counts": dict(sorted(state["util"].items(), key=lambda x:-x[1])),
}
with open(PROG,"w",encoding="utf-8") as fh:
json.dump(snap, fh, indent=2)
def recipes_by_cat():
d = {"single":[],"pipeline":[],"script":[]}
for r in RECIPES:
d[r["category"]].append(r)
return d
RBC = recipes_by_cat()
def choose_category(state):
rem = {c: CAT_TARGET[c]-state["cat"].get(c,0) for c in CAT_TARGET}
rem = {c:v for c,v in rem.items() if v>0}
if not rem:
return None
cats = list(rem); weights = list(rem.values())
return random.choices(cats, weights=weights, k=1)[0]
def choose_recipe(cat, state):
pool = [r for r in RBC[cat] if state["util"].get(r["utility"],0) < UTIL_CAP]
if not pool:
return None
return random.choices(pool, weights=[r["weight"] for r in pool], k=1)[0]
def choose_deficit_recipe(merged, cat_now):
"""Bias generation toward utilities still below their MIN_UTIL floor.
Returns (recipe, category) or None. Only picks recipes whose category
still has quota left, so it never violates category targets."""
deficits = {u: MIN_UTIL[u]-merged.get(u,0)
for u in MIN_UTIL if merged.get(u,0) < MIN_UTIL[u]}
if not deficits:
return None
u = random.choices(list(deficits), weights=list(deficits.values()), k=1)[0]
recs = [r for r in RECIPES
if r["utility"] == u
and cat_now.get(r["category"],0) < CAT_TARGET[r["category"]]]
if not recs:
return None
r = random.choices(recs, weights=[rr["weight"] for rr in recs], k=1)[0]
return r, r["category"]
def bash_n_batch(snippets):
"""Return list of bools (valid?) for each snippet. Uses combined function-wrap;
falls back to per-snippet on failure."""
os.makedirs(VALID_DIR, exist_ok=True)
combined = os.path.join(VALID_DIR, "combined.sh")
with open(combined,"w",encoding="utf-8",newline="\n") as fh:
for i,s in enumerate(snippets):
fh.write(f"__v{i}() {{\n{s}\n}}\n")
r = subprocess.run([BASH,"-n",combined], capture_output=True, text=True)
if r.returncode == 0:
return [True]*len(snippets)
# fallback: check each individually
res = []
for i,s in enumerate(snippets):
p = os.path.join(VALID_DIR, f"s{i}.sh")
with open(p,"w",encoding="utf-8",newline="\n") as fh:
fh.write(s+"\n")
rr = subprocess.run([BASH,"-n",p], capture_output=True, text=True)
res.append(rr.returncode==0)
return res
def generate_batch(state, batch_size):
cand = []
provisional_util = {}
provisional_cat = {}
attempts = 0
max_attempts = batch_size*80
while len(cand) < batch_size and attempts < max_attempts:
attempts += 1
# merged util + category views (include provisional within this batch)
merged = dict(state["util"])
for u,v in provisional_util.items():
merged[u] = merged.get(u,0)+v
cat_now = {c:state["cat"].get(c,0)+provisional_cat.get(c,0) for c in CAT_TARGET}
# Floor pass: 60% of the time, preferentially fill under-floor utilities.
# Probabilistic so an unreachable floor can never stall the batch.
rec = cat = None
if random.random() < 0.6:
dr = choose_deficit_recipe(merged, cat_now)
if dr is not None:
rec, cat = dr
if rec is None:
cat = choose_category({"cat":cat_now})
if cat is None:
break
rec = choose_recipe(cat, {"util":merged})
if rec is None:
continue
res = rec["fn"]()
if len(res) == 3:
nl, bash, util = res # recipe supplied a dynamic utility
else:
nl, bash = res
util = rec["utility"]
nl = diversify_nl(nl) # break up the dominant script opening
# enforce the real per-utility cap (works even for dynamic labels)
if merged.get(util, 0) >= UTIL_CAP:
continue
# HARD GATE: the command must actually reference the concrete nouns
# (files, extensions, users, groups, services, procs, ports) named in
# the request. Guarantees argument fidelity regardless of recipe bugs.
if arg_mismatch(nl, bash):
continue
h = hashlib.sha1((nl+"\x00"+bash).encode()).hexdigest()
if h in state["seen"]:
continue
state["seen"].add(h)
cand.append({"nl":nl,"bash":bash,"category":rec["category"],
"utility":util,"_h":h})
provisional_util[util] = provisional_util.get(util,0)+1
provisional_cat[cat] = provisional_cat.get(cat,0)+1
if not cand:
return 0, 0
# syntax check
valid = bash_n_batch([c["bash"] for c in cand])
kept = []
dropped = 0
for c,ok in zip(cand, valid):
if ok:
kept.append(c)
else:
dropped += 1
state["seen"].discard(c["_h"])
# append to disk in chat-messages ("final") form, with metadata kept
# alongside for quota tracking / resume (trainers just read "messages").
with open(OUT,"a",encoding="utf-8") as fh:
for c in kept:
row = {"messages":[
{"role":"system","content":R(SYSTEM_PROMPTS)},
{"role":"user","content":c["nl"]},
{"role":"assistant","content":c["bash"]},
],
"category":c["category"],"utility":c["utility"]}
fh.write(json.dumps(row, ensure_ascii=False)+"\n")
state["total"] += 1
state["cat"][c["category"]] = state["cat"].get(c["category"],0)+1
state["util"][c["utility"]] = state["util"].get(c["utility"],0)+1
save_progress(state)
return len(kept), dropped
def cmd_status(state):
print(f"total written: {state['total']} / {TARGET_TOTAL}")
for c in CAT_TARGET:
print(f" {c:9s}: {state['cat'].get(c,0):6d} / {CAT_TARGET[c]}")
print(f"distinct utilities: {len(state['util'])}, cap per utility: {UTIL_CAP}")
over = [(u,n) for u,n in state['util'].items() if n>UTIL_CAP]
if over: print(" OVER CAP:", over)
top = sorted(state['util'].items(), key=lambda x:-x[1])[:12]
print(" top utilities:", ", ".join(f"{u}={n}" for u,n in top))
floors = {u: (state['util'].get(u,0), m) for u,m in MIN_UTIL.items()}
unmet = {u:v for u,v in floors.items() if v[0] < v[1]}
print(" info-util floors:", ", ".join(f"{u}={v[0]}/{v[1]}" for u,v in sorted(floors.items())))
print(" floors unmet:", unmet if unmet else "NONE")
def cmd_plan(state):
print(f"TARGET {TARGET_TOTAL} | util cap {UTIL_CAP} ({UTIL_CAP/TARGET_TOTAL*100:.0f}%)")
print("category target have short")
for c in CAT_TARGET:
have = state["cat"].get(c,0)
print(f" {c:9s} {CAT_TARGET[c]:7d} {have:6d} {max(0,CAT_TARGET[c]-have):6d}")
print(f"recipes registered: {len(RECIPES)} "
f"(single={len(RBC['single'])}, pipeline={len(RBC['pipeline'])}, script={len(RBC['script'])})")
utils = sorted({r['utility'] for r in RECIPES})
print(f"distinct utilities in recipe set: {len(utils)}")
print(" ", ", ".join(utils))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("cmd", choices=["status","plan","run","validate-all"])
ap.add_argument("--batch", type=int, default=500)
ap.add_argument("--batches", type=int, default=1)
ap.add_argument("--target", type=int, default=None)
args = ap.parse_args()
state = load_state()
if args.target:
globals()["TARGET_TOTAL"] # keep simple; target override not persisted
if args.cmd == "status":
cmd_status(state); return
if args.cmd == "plan":
cmd_plan(state); return
if args.cmd == "validate-all":
snippets=[];
with open(OUT,encoding="utf-8") as fh:
for line in fh:
line=line.strip()
if line: snippets.append(row_nl_bash(json.loads(line))[1])
res = bash_n_batch(snippets)
bad = sum(1 for x in res if not x)
print(f"validated {len(snippets)} snippets, {bad} syntax failures")
return
if args.cmd == "run":
for b in range(args.batches):
kept, dropped = generate_batch(state, args.batch)
print(f"batch {b+1}/{args.batches}: +{kept} kept, {dropped} dropped "
f"| total {state['total']} "
f"(single {state['cat']['single']}, pipeline {state['cat']['pipeline']}, script {state['cat']['script']})")
if kept == 0:
print("no more can be generated (quota/cap/dedup exhausted) — stopping")
break
if __name__ == "__main__":
main()