#!/usr/bin/env bash
# Common Linux commands in practice: answer several operations questions using a synthetic LLM gateway access log.
set -euo pipefail
W=$(mktemp -d); cd "$W"
"${PY:-python3}" - <<'P'
import random; random.seed(6)
paths = ["/v1/chat"] * 7 + ["/v1/embed"] * 2 + ["/health"]
with open("gateway.log", "w") as f:
for i in range(2000):
p = random.choice(paths); code = random.choices([200, 429, 500, 401], [90, 6, 2, 2])[0]
ms = int(random.lognormvariate(5.5 if p == "/v1/chat" else 3.5, 0.6)); user = f"u{random.randint(1, 40):02d}"
f.write(f"2026-10-14T{8 + i * 12 // 2000:02d}:{(i * 7) % 60:02d}:00+08:00 {user} POST {p} {code} {ms}ms\n")
P
echo "== Quick inspection: head / wc"
head -3 gateway.log; wc -l gateway.log; ls -lh gateway.log | awk '{print "Size:", $5}'
echo "== ① Status code distribution: awk column 5 -> sort -> uniq -c -> sort descending by count"
awk '{print $5}' gateway.log | sort | uniq -c | sort -rn
echo "== ② Top 3 rate-limited (429) users"
grep ' 429 ' gateway.log | awk '{print $2}' | sort | uniq -c | sort -rn | head -3
echo "== ③ /v1/chat latency P50 / P95 / max (ms)"
grep ' /v1/chat ' gateway.log | awk '{gsub("ms","",$6); print $6}' | sort -n > lat.txt
n=$(wc -l < lat.txt); echo "Samples $n P50=$(sed -n "$(((n*50+99)/100))p" lat.txt) P95=$(sed -n "$(((n*95+99)/100))p" lat.txt) max=$(tail -1 lat.txt)"
echo "== ④ Hourly 5xx error counts"
awk '$5 ~ /^5/ {print substr($1, 12, 2) "h"}' gateway.log | sort | uniq -c | tr '\n' ' '; echo
echo "== ⑤ Live tailing: tail -f + grep --line-buffered (using timeout to exit after 1 second)"
( sleep 0.3; echo "2026-10-14T21:00:00+08:00 u99 POST /v1/chat 500 9999ms" >> gateway.log ) &
timeout 1 tail -n 0 -f gateway.log | grep --line-buffered ' 500 ' || true
echo "== ⑥ find + xargs: locate logs larger than 10KB and compress them"
for i in 1 2 3; do head -c $((i * 5000)) /dev/urandom | base64 > "old-$i.log"; done
find . -name 'old-*.log' -size +10k -print0 | sort -z | xargs -0 -n1 gzip -v 2>&1 | sed 's/^/ /'
ls old-* | tr '\n' ' '; echo
echo "== ⑦ Permissions: when a script lacks execute permission"
printf '#!/bin/sh\necho Execution succeeded\n' > run.sh; ls -l run.sh | cut -d' ' -f1
./run.sh 2>&1 || true; chmod u+x run.sh; ls -l run.sh | cut -d' ' -f1; ./run.sh
rm -rf "$W"
Example Script: 22_linux_commands.sh
Original companion example or verification log for the tutorial, preserved with user paths redacted; execution scope follows the recorded run.