Creating an Optimised Ubuntu Swap Space with one simple script

A quick search on Google with throw up loads on swap files, if you want to read about what they are and how they work there is a good article over at Ubuntu help

If you want a good step by step setup guide explaining how to achieve each of the steps in the script manually head on over to the Digital Ocean setup article

Below is a script that automates all of the steps and results in everything being setup correctly.

Automated Swap File Setup Script

Create a file called swap and add the following to the file.

#!/bin/sh

# Do argument checks
if [ ! "$#" -ge 1 ]; then
 echo "Usage: $0 {size}"
 echo "Example: $0 2G"
 echo "Optional path: Usage: $0 {size} {path}"
 exit 1
fi


# Messages
echo "=========================================================="
echo "Welcome to CraftThatBlock's Ubuntu Swap install script!"
echo "This script will automatically setup a swap file,"
echo "install it, and do everything else needed."
echo "All you have to do is enter your password and hit enter!"
echo "=========================================================="
echo ""

# Setup variables
SWAP_SIZE=$1
SWAP_PATH="/swapfile"
if [ ! -z "$2" ]; then
 SWAP_PATH=$2
fi


# Start script
sudo fallocate -l $SWAP_SIZE $SWAP_PATH #if fallocate doesn't work comment out this line and uncomment the line below
#sudo dd if=/dev/zero of=$SWAP_PATH bs=$SWAP_SIZE count=1
sudo chmod 600 $SWAP_PATH
sudo mkswap $SWAP_PATH
sudo swapon $SWAP_PATH
echo "$SWAP_PATH none swap sw 0 0" | sudo tee /etc/fstab -a
sudo sysctl vm.swappiness=10
echo "vm.swappiness=10" | sudo tee /etc/sysctl.conf -a
sudo sysctl vm.vfs_cache_pressure=50
echo "vm.vfs_cache_pressure=50" | sudo tee /etc/sysctl.conf -a


# Done
echo ""
echo "=========================================================="
echo "Done! The apply these changes you simply have to restart:"
echo "sudo reboot now"
echo "=========================================================="
echo ""

Upload it to your root folder /root/swap

Then simply run the file with this format:

sh swap {size}

Example (2G is enough usually):

sh swap 2G

The default path for the swap file is /swapfile. If you wish to change this, simple the file location (FILE MUST NOT EXIST) add it to the command:

sh swap 2G /swapfile

based on and with thanks to CraftThatBlocks code

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.