Skip to content

Instantly share code, notes, and snippets.

@xeruf
Forked from Jekis/toggle_swap.sh
Last active December 11, 2019 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeruf/78f12b64c916bb9e6a82ea622f21d06c to your computer and use it in GitHub Desktop.
Save xeruf/78f12b64c916bb9e6a82ea622f21d06c to your computer and use it in GitHub Desktop.
Empty Swap. Can be put into ~/.bashrc or similar and then called with stopswap.
mem_stat() {
mem_total="$(free | head -2 | tail -1 | awk '{print $2}')"
mem_free="$(free | head -2 | tail -1 | awk '{print $4}')"
mem_percentage=$((mem_free * 100 / $mem_total))
swap_total="$(free | tail -1 | awk '{print $2}')"
swap_used="$(free | tail -1 | awk '{print $3}')"
swap_percentage=$(($swap_used * 100 / $swap_total))
echo -e "Free memory:\t$((mem_free / 1024))/$((mem_total / 1024)) MB\t($mem_percentage%)"
echo -e "Used swap:\t$((swap_used / 1024))/$((swap_total / 1024)) MB\t($swap_percentage%)"
}
stopswap() {
mem_stat
if (( $swap_used == 0 ))
then echo "No swap is in use."
elif (( $swap_used + 100000 < mem_free ))
then echo "Freeing swap..."
sudo swapoff -a
sudo swapon -a
mem_stat
else
echo "Not enough free memory!"
fi
}
@xalt7x
Copy link

xalt7x commented Dec 11, 2019

Scripts is a little incorrect and doesn't always work with low RAM size.
mem_free="$(free | head -2 | tail -1 | awk '{print $4}')"
With 2GB RAM and ~580MB used (according to htop) command shows that I have only 94MB of free memory so script refuses to clear swap.

image

I guess it's better to print "available" memory (like in Jekis version)
mem_free="$(free | head -2 | tail -1 | awk '{print $7}')"

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