Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Last active December 16, 2015 22:19
Show Gist options
  • Save izmailoff/5506056 to your computer and use it in GitHub Desktop.
Save izmailoff/5506056 to your computer and use it in GitHub Desktop.
Flashes swap memory by disabling and then enabling all swap devices. It first performs a check if enough memory is available on the system. Then it syncs all dirty buffers and disables/enables swap. Motivation is to be able to quickly force swap data into memory without waiting for OS to do it. Probably, you should not need this on a healthy ser…
#!/bin/bash
function printDebug()
{
if [ ! -z "$debug" ]; then
echo "$1"
fi
}
debug="$1"
memFree=$(egrep '^MemFree:' /proc/meminfo | awk '{print $2}')
memCached=$(egrep '^Cached:' /proc/meminfo | awk '{print $2}')
memAvailable=$(expr "$memFree" + "$memCached")
swapTotal=$(egrep '^SwapTotal:' /proc/meminfo | awk '{print $2}')
swapFree=$(egrep '^SwapFree:' /proc/meminfo | awk '{print $2}')
swapUsed=$(expr "$swapTotal" - "$swapFree")
if [ ! -z "$debug" ]; then
memTotal=$(egrep '^MemTotal' /proc/meminfo | awk '{print $2}')
echo "Total memory: $memTotal"
echo "Free: $memFree"
echo "Cached: $memCached"
echo "Available: $memAvailable"
echo "Swapped: $swapUsed"
echo
fi
if [ "$swapUsed" -eq "0" ]; then
printDebug "NO NEED TO FLASH, SWAP USES 0 BYTES."
elif [ "$memAvailable" -gt "$swapUsed" ]; then
printDebug "FLASHING SWAP..."
sync && swapoff -a && swapon -a
printDebug "DONE."
else
printDebug "NOT ENOUGH FREE MEMORY."
exit 1
fi
@izmailoff
Copy link
Author

For more conservative use replace:

if [ "$memAvailable" -gt "$swapUsed" ]

with

if [ "$memFree" -gt "$swapUsed" ]

This "conservative option" will not affect cached disk pages.

Run as sudo:

sudo swapnuke.sh

or with more verbosity (my preference):

sudo swapnuke.sh v

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment