#!/usr/bin/env bash
# Linux 常用命令实战:用一份(虚构的)LLM 网关访问日志,回答几个运维问题。
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 "== 先看一眼:head / wc"
head -3 gateway.log; wc -l gateway.log; ls -lh gateway.log | awk '{print "大小:", $5}'
echo "== ① 状态码分布:awk 取第 5 列 → sort → uniq -c → 按次数倒序"
awk '{print $5}' gateway.log | sort | uniq -c | sort -rn
echo "== ② 被限流(429)最多的 3 个用户"
grep ' 429 ' gateway.log | awk '{print $2}' | sort | uniq -c | sort -rn | head -3
echo "== ③ /v1/chat 的延迟 P50 / P95 / 最大值(ms)"
grep ' /v1/chat ' gateway.log | awk '{gsub("ms","",$6); print $6}' | sort -n > lat.txt
n=$(wc -l < lat.txt); echo "样本数 $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 "== ④ 按小时统计 5xx 错误数"
awk '$5 ~ /^5/ {print substr($1, 12, 2) "时"}' gateway.log | sort | uniq -c | tr '\n' ' '; echo
echo "== ⑤ 实时追踪:tail -f + grep --line-buffered(这里用 timeout 让它 1 秒后结束)"
( 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:找出大于 10KB 的日志并压缩"
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 "== ⑦ 权限:脚本没有执行权限时"
printf '#!/bin/sh\necho 运行成功\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"
示例文件:22_linux_commands.sh
与教程配套的原始示例或核验资料,保留完整内容;其中真实用户目录已脱敏,运行范围以记录本身为准。