添加SWAP占用率查询脚本

This commit is contained in:
CN-JS-HuiBai
2026-02-23 19:55:13 +08:00
parent 5768d6d9e2
commit afadfffda2

View File

@@ -0,0 +1,27 @@
#!/bin/bash
# 获取总 Swap单位 kB
total_swap_kb=$(grep SwapTotal /proc/meminfo | awk '{print $2}')
if [ "$total_swap_kb" -eq 0 ]; then
echo "系统未启用 Swap"
exit 1
fi
printf "%-8s %-12s %-25s %-12s %-8s\n" "PID" "USER" "PROCESS" "SWAP(MB)" "USAGE%"
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
if [ -r /proc/$pid/status ]; then
swap_kb=$(grep VmSwap /proc/$pid/status 2>/dev/null | awk '{print $2}')
if [ ! -z "$swap_kb" ] && [ "$swap_kb" -gt 0 ]; then
user=$(ps -o user= -p $pid 2>/dev/null)
comm=$(ps -o comm= -p $pid 2>/dev/null)
swap_mb=$(awk "BEGIN {printf \"%.2f\", $swap_kb/1024}")
percent=$(awk "BEGIN {printf \"%.2f\", ($swap_kb/$total_swap_kb)*100}")
printf "%-8s %-12s %-25s %-12s %-8s\n" \
"$pid" "$user" "$comm" "$swap_mb" "$percent"
fi
fi
done | sort -k4 -nr