Files
Linux-Shell/archrived-shells/showswap.sh
2026-02-23 19:55:13 +08:00

27 lines
913 B
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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