Skip to content

Instantly share code, notes, and snippets.

@lovesitdoll
Forked from memduhcagridemir/enable-swap.sh
Created September 15, 2018 18:12
Show Gist options
  • Save lovesitdoll/ffdbe51bf2e6ad87d72eadfd5643e387 to your computer and use it in GitHub Desktop.
Save lovesitdoll/ffdbe51bf2e6ad87d72eadfd5643e387 to your computer and use it in GitHub Desktop.
#!/bin/bash
##
# Usage
# # enable-swap.sh 1024M
##
SWAPFILE="/swapfile.swp"
SWAPSIZE=$1
die () {
RED='\033[0;31m'
NC='\033[0m'
echo -e >&2 "${RED}$@${NC}\n"
exit 1
}
[ "$(id -u)" -eq "0" ] || die "This script must be run as root"
[ "$#" -eq 1 ] || die "Swap size parameter required, $# argument provided"
echo $1 | grep -E -q '^[0-9]+(B|K|M|G|T)$' || die "Swap size should look like 1024M or 2G, $1 is WRONG"
[ ! -f $SWAPFILE ] || die "Swap file exists, disable swap first"
free | grep -E -q "^Swap:[[:blank:]]*0"
[ $? -eq 0 ] || die "Swap is already enabled."
fallocate -l "$SWAPSIZE" $SWAPFILE
[ $? -eq 0 ] || die "Unable to fallocate $SWAPFILE"
chmod 600 $SWAPFILE
[ $? -eq 0 ] || die "Unable to chmod 600 $SWAPFILE"
mkswap $SWAPFILE
[ $? -eq 0 ] || die "Unable to mkswap $SWAPFILE"
swapon $SWAPFILE
[ $? -eq 0 ] || die "Unable to swapon $SWAPFILE"
echo "$SWAPFILE none swap sw 0 0" | tee -a /etc/fstab
[ $? -eq 0 ] || die "Unable to write to fstab $SWAPFILE"
sysctl vm.swappiness=10
[ $? -eq 0 ] || die "Unable to adjust swappiness $SWAPFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment