Skip to content

Instantly share code, notes, and snippets.

@allenk
Created April 16, 2024 14:04
Show Gist options
  • Save allenk/7ff3035fce996846e1bd45334c0cdb29 to your computer and use it in GitHub Desktop.
Save allenk/7ff3035fce996846e1bd45334c0cdb29 to your computer and use it in GitHub Desktop.
WSL2 Cache Memory Auto Release
#!/bin/bash
# Memory threshold
THRESHOLD_AVAIL=10 # MemAvailable
THRESHOLD_FREE=10 # Free
# Loop to test memory
while true; do
# fetech memory status
TOTAL_MEM=$(grep MemTotal /proc/meminfo | awk '{print $2 / 1024}')
AVAIL_MEM=$(grep MemAvailable /proc/meminfo | awk '{print $2 / 1024}')
FREE_MEM=$(grep MemFree /proc/meminfo | awk '{print $2 / 1024}')
# comput the usage of memory
AVAIL_MEM_PCT=$(echo "scale=2; $AVAIL_MEM / $TOTAL_MEM * 100" | bc)
FREE_MEM_PCT=$(echo "scale=2; $FREE_MEM / $TOTAL_MEM * 100" | bc)
# check memory
if (( $(echo "$AVAIL_MEM_PCT < $THRESHOLD_AVAIL" | bc -l) )) || (( $(echo "$FREE_MEM_PCT < $THRESHOLD_FREE" | bc -l) )); then
echo "Memory cleanup trigger: MemAvailable: $AVAIL_MEM_PCT%, Free: $FREE_MEM_PCT%"
# clean memory
echo 3 > /proc/sys/vm/drop_caches
swapoff -a
swapon -a
echo "The cache has been cleared!"
else
echo "Memory StatusMemAvailable: $AVAIL_MEM_PCT%, Free: $FREE_MEM_PCT%"
fi
# Wait a while for next check
sleep 60
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment