Skip to content

Instantly share code, notes, and snippets.

@jpriebe
Last active September 9, 2016 12:38
Show Gist options
  • Save jpriebe/aa52fee9f07c013523fc932a68b77f78 to your computer and use it in GitHub Desktop.
Save jpriebe/aa52fee9f07c013523fc932a68b77f78 to your computer and use it in GitHub Desktop.
#!/bin/sh
####---------------------------------------------------------------------------
#### fix_swap.sh
####
#### designed for use with CentOS 7; we have noticed that our CentOS 7
#### hosts often use large amounts of swap when plenty of memory is
#### available. This causes false alarms in our system monitoring software
#### (zabbix).
####
#### this script reconfigures the system to be less swappy, and it
#### frees up the swap that is currently in use, if there's enough RAM.
####
#### thanks to Scott Severence for the code to safely free up swap
#### (http://askubuntu.com/questions/1357/how-to-empty-swap-if-there-is-free-ram)
####---------------------------------------------------------------------------
echo "" >> /etc/sysctl.conf
echo "# reduce the system's tendency to swap out (we keep filling up swap" >> /etc/sysctl.conf
echo "# with plenty of RAM remaining; this trips unnecessary zabbix alerts)" >> /etc/sysctl.conf
echo "vm.swappiness = 1" >> /etc/sysctl.conf
sysctl vm.swappiness=1
free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"
echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"
if [[ $used_swap -eq 0 ]]; then
echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $total_free ]]; then
echo "Freeing swap..."
sudo swapoff -a
sudo swapon -a
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