refactor(zram): 模块化 zram 脚本并引入通用加载机制支持远程调用

This commit is contained in:
严浩
2026-03-23 11:10:15 +08:00
parent 88603904c0
commit 2978818923
3 changed files with 190 additions and 136 deletions
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
format_zram_bytes() {
awk -v bytes="$1" 'BEGIN {
split("B KiB MiB GiB TiB PiB", units, " ")
idx = 1
while (bytes >= 1024 && idx < 6) {
bytes /= 1024
idx++
}
printf "%.2f %s", bytes, units[idx]
}'
}
show_zram_status() {
echo "========== zram 运行战报 =========="
if ! command -v zramctl >/dev/null 2>&1; then
echo "未安装 zramctl。"
return 1
fi
local table
table=$(zramctl --noheadings --output NAME,ALGORITHM,DISKSIZE,DATA,COMPR,TOTAL,COMP-RATIO,MOUNTPOINT 2>/dev/null || true)
if [ -z "$table" ]; then
echo "未发现活跃的 zram 设备。"
return 0
fi
printf '%s\n' "$table"
local stats
stats=$(zramctl --bytes --raw --noheadings --output DATA,COMPR,TOTAL 2>/dev/null || true)
if [ -z "$stats" ]; then
echo "未发现活跃的 zram 设备。"
return 0
fi
local data_size compr_size total_mem saved_bytes ratio
read -r data_size compr_size total_mem <<EOF
$(printf '%s\n' "$stats" | awk '{data += $1; compr += $2; total += $3} END {print data+0, compr+0, total+0}')
EOF
if [ "$total_mem" -le 0 ]; then
echo "当前 zram 尚无可统计的数据。"
return 0
fi
saved_bytes=$((data_size - total_mem))
if [ "$saved_bytes" -lt 0 ]; then
saved_bytes=0
fi
ratio=$(awk -v data="$data_size" -v total="$total_mem" 'BEGIN { printf "%.2f", data / total }')
echo "----------- 汇总 -----------"
echo "1. 原始数据量: $(format_zram_bytes "$data_size")"
echo "2. 压缩后大小: $(format_zram_bytes "$compr_size")"
echo "3. 实际占用内存: $(format_zram_bytes "$total_mem")"
echo "4. 压缩倍率: ${ratio}x"
echo "5. 为系统节省了: $(format_zram_bytes "$saved_bytes") 物理内存"
echo "==================================="
}
if [ "${BASH_SOURCE[0]:-}" = "$0" ] || [ -z "${BASH_SOURCE[0]:-}" ]; then
show_zram_status
fi