Skip to content

Instantly share code, notes, and snippets.

@movalex
Forked from Jekis/toggle_swap.sh
Last active September 6, 2022 09:18
Show Gist options
  • Save movalex/ba4e94eb0e03e4cff151162bc3e657aa to your computer and use it in GitHub Desktop.
Save movalex/ba4e94eb0e03e4cff151162bc3e657aa to your computer and use it in GitHub Desktop.
Empty swap. Clear swap. Move swap to RAM. Ubuntu.
#!/bin/bash
function calc_percentage () {
mem="$1"
total="$2"
if [[ $mem -gt 0 ]]; then
return $((mem * 100 / total))
else
return 0
fi
}
function echo_mem_stat () {
mem_total="$(free | grep 'Mem:' | awk '{print $2}')"
free_mem="$(free | grep 'Mem:' | awk '{print $7}')"
mem_percentage=$(calc_percentage $free_mem $mem_total)
swap_total="$(free | grep 'Swap:' | awk '{print $2}')"
used_swap="$(free | grep 'Swap:' | awk '{print $3}')"
swap_percentage=$(calc_percentage $used_swap $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 ] || [ "$swap_percentage" -lt 5 ]; then
echo "No need to free swap"
elif [[ $used_swap -lt $free_mem ]]; then
echo "Freeing swap..."
swapoff -a
swapon -a
echo_mem_stat
else
echo "Not enough free memory. Exiting."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment