Skip to content

Instantly share code, notes, and snippets.

@arenadoon
Forked from Jekis/toggle_swap.sh
Last active August 23, 2024 11:35
Show Gist options
  • Save arenadoon/27fc93713c05a89bda5466e273137844 to your computer and use it in GitHub Desktop.
Save arenadoon/27fc93713c05a89bda5466e273137844 to your computer and use it in GitHub Desktop.
Empty swap. Clear swap. Move swap to RAM. Ubuntu.
#!/bin/bash
#https://gist.github.com/arenadoon/27fc93713c05a89bda5466e273137844 <--my
#https://gist.github.com/Jekis/6c8fe9dfb999fa76479058e2d769ee5c <--Default
function echo_mem_stat () {
mem_total="$(free | grep 'Mem:' | awk '{print $2}')"
free_mem="$(free | grep 'Mem:' | awk '{print $7}')"
mem_percentage=$(($free_mem * 100 / $mem_total))
swap_total="$(free | grep 'Swap:' | awk '{print $2}')"
used_swap="$(free | grep 'Swap:' | awk '{print $3}')"
swap_percentage=$(($used_swap * 100 / $swap_total))
echo -e "Free memory:\t$((free_mem / 1024))/$((mem_total / 1024)) MB\t($mem_percentage%)"
echo -e "Used swap:\t$((used_swap / 1024))/$((swap_total / 1024)) MB\t($swap_percentage%)"
}
echo "Testing..."
echo_mem_stat
if [[ $used_swap -eq 0 ]]; then
echo `date`
echo "No swap is in use."
elif [[ $used_swap -lt $free_mem ]]; then
echo "Freeing swap..."
swapoff -a
swapon -a
echo_mem_stat
echo "=========="
echo `date`
echo "=========="
else
echo "Not enough free memory. Exiting."
echo `date`
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment