summaryrefslogtreecommitdiff
path: root/bin/swap
diff options
context:
space:
mode:
Diffstat (limited to 'bin/swap')
-rwxr-xr-xbin/swap75
1 files changed, 75 insertions, 0 deletions
diff --git a/bin/swap b/bin/swap
new file mode 100755
index 0000000..b3a9a31
--- /dev/null
+++ b/bin/swap
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# order by
+by="swap"
+
+# reverse sort
+rev="r"
+
+if [ ! -z "$1" ]; then
+ case "$1" in
+ -s|--swap|swap)
+ by="swap"
+ shift
+ ;;
+ -m|--memory|mem|memory)
+ by="memory"
+ shift
+ ;;
+ -n|--name|-p|--process|--program|name|proc|process)
+ by="name"
+ rev=""
+ shift
+ ;;
+ -h|--help|help)
+ echo "Statistics about memory and swap usage from all running processes."
+ echo "Usage: $0 [OPTION]"
+ echo " swap sort by swap usage (default)"
+ echo " memory sort by memory usage"
+ echo " name sort by process name"
+ echo " help print this help message"
+ exit 0
+ ;;
+ *)
+ echo "Unrecognized option \"$1\"" >&2
+ echo "Try \"-h\" instead."
+ exit 1
+ esac
+fi
+
+echo "Check memory and swap usage for all programs sorted by $by."
+echo "$(tput setaf 1)Attention! The reported memory usage is just the $(tput bold)virtual$(tput sgr0) $(tput setaf 1)usage, not the $(tput bold)real$(tput sgr0) $(tput setaf 1)one."
+echo "Read more about this on Wikipedia. $(tput bold)https://en.wikipedia.org/wiki/Virtual_memory$(tput sgr0)"
+echo ""
+
+# loop over all running programs
+for CMD in $(top -bn1 | tail -n +8 | grep -v $(basename "$0") | awk '{print $12}' | sort | uniq)
+do
+ swap_count=0
+ mem_count=0
+
+ # loop over all pids and check for 'VmSize' and 'VmSwap' state in /proc/$PID/status
+ for tmp in $( for PID in $(pgrep $CMD 2>/dev/null); do grep -E 'Vm(Size|Swap)' /proc/$PID/status 2>/dev/null | paste - - | awk '{print $2 "|" $5}'; done )
+ do
+ mem_count=$(($mem_count+$(echo $tmp | cut -d\| -f1)))
+ swap_count=$(($swap_count+$(echo $tmp | cut -d\| -f2)))
+ done
+
+ # programs swap or memory use is not null
+ if [ $swap_count -gt 0 ] || [ $mem_count -gt 0 ]
+ then
+ case "$by" in
+ swap)
+ echo "$swap_count kB (Swap): $CMD $mem_count kB (Memory)"
+ ;;
+ memory)
+ echo "$mem_count kB (Memory): $CMD $swap_count kB (Swap)"
+ ;;
+ name)
+ echo "$CMD: $mem_count kB (Memory) $swap_count kB (Swap)"
+ ;;
+ esac
+ fi
+
+# sorting and formatting output
+done | sort -k1 -t\ -h${rev} | column -t