dotfiles/.local/bin/mod-memory
2024-09-05 22:35:28 -04:00

54 lines
1.2 KiB
Bash
Executable file

#!/bin/sh
set -eu
DISPLAY_DECIMAL_PLACES=2
MEBI=1024
GIBI=$((MEBI * MEBI))
TEBI=$((GIBI * MEBI))
display_kib_unit() {
size_kib=$1
decimal_places=$2
if [ "$size_kib" -lt "$MEBI" ]; then
size=$size_kib
unit="K"
elif [ "$size_kib" -lt "$GIBI" ]; then
size=$(printf 'scale=%s; %s / %s\n' "$decimal_places" "$size_kib" "$MEBI" | bc)
unit="M"
elif [ "$size_kib" -lt "$TEBI" ]; then
size=$(printf 'scale=%s; %s / %s\n' "$decimal_places" "$size_kib" "$GIBI" | bc)
unit="G"
else
size=$(printf 'scale=%s; %s / %s\n' "$decimal_places" "$size_kib" "$TEBI" | bc)
unit="T"
fi
printf '%.*f%s' "$decimal_places" "$size" "$unit"
}
mem_total=
mem_free=
mem_buffers=
mem_cached=
mem_sreclaimable=
mem_shmem=
while read -r type value _; do
case $type in
MemTotal:) mem_total=$value ;;
MemFree:) mem_free=$value ;;
Buffers:) mem_buffers=$value ;;
Cached:) mem_cached=$value ;;
SReclaimable:) mem_sreclaimable=$value ;;
Shmem:) mem_shmem=$value ;;
esac
done </proc/meminfo
mem_used=$((mem_total - mem_free))
mem_non_cache_buffer=$((mem_used - (mem_buffers + (mem_cached + mem_sreclaimable - mem_shmem))))
printf 'MEM %s' $(display_kib_unit "$mem_non_cache_buffer" "$DISPLAY_DECIMAL_PLACES")