Files
Linux/show_zram_status.sh
T

73 lines
1.9 KiB
Bash

#!/usr/bin/env bash
#
# ...
#
# 使用方法:
# URL="https://git.1-h.cc/Scripts/Linux/raw/branch/2026/show_zram_status.sh"; curl -fsSL "$URL" | bash
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 }')
format_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]
}'
}
echo "----------- 汇总 -----------"
echo "1. 原始数据量: $(format_bytes "$data_size")"
echo "2. 压缩后大小: $(format_bytes "$compr_size")"
echo "3. 实际占用内存: $(format_bytes "$total_mem")"
echo "4. 压缩倍率: ${ratio}x"
echo "5. 为系统节省了: $(format_bytes "$saved_bytes") 物理内存"
echo "==================================="
}
show_zram_status