Auto clear SWAP in Linux

Auto clear SWAP in Linux

This script will simply drop cache and clear SWAP, you can use it by scheduling it on a daily basis:

# crontab -e
0 2 * * * echo 1 >  /proc/sys/vm/drop_caches & &  swapoff -a & &  swapon -a

Check if SWAP is more than 20%

Set the script to run every 5 minutes:

# crontab -e
*/5 * * * * clearswap.sh

This script will check if the SWAP usage is above a threshold (20%) and if so, clear it:

#/bin/bash

LIMIT=(20);

swap() {
    SWAP_USAGE=$(free -t | awk 'FNR == 3 {print $3/$2*100}');
    SWAP_USAGE_NO_DECIMALS=$(printf %.0f $SWAP_USAGE)
    TIME=$(date);
    if [ "$SWAP_USAGE_NO_DECIMALS" -gt "$LIMIT" ]; then
       echo 1 > /proc/sys/vm/drop_caches
	   sudo swapoff -a; sudo swapon -a
    else
    fi
}
whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.