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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#!/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:
1 |
sh swap {size} |
Example (2G is enough usually):
1 |
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:
1 |
sh swap 2G /swapfile |
based on and with thanks to CraftThatBlocks code
Recent Comments