Skip to content

Instantly share code, notes, and snippets.

@bouroo
Last active March 17, 2024 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bouroo/420bb89c3237b29ff3cd7e01bb1feb96 to your computer and use it in GitHub Desktop.
Save bouroo/420bb89c3237b29ff3cd7e01bb1feb96 to your computer and use it in GitHub Desktop.
Create swap on VPS
#!/usr/bin/env bash
#==============================================================================
# title: swap.sh
# description: This script automatically creates a swap size that's 20% of total RAM
# and comments out the old swap device in /etc/fstab.
# author: Kawin Viriyaprasopsook <kawin.v@kkumail.com>
# usage: bash swap.sh
# notes: need `sudo dd sed` packages
#==============================================================================
if [ "$(whoami)" != "root" ]; then
SUDO=sudo
fi
# Disable the existing swap devices
${SUDO} swapoff -a
# Get the amount of RAM in MB
ram_mb=$(free -m | awk '/Mem:/ {print $2}')
# Calculate the swap size in MB (20% of RAM)
swap_mb=$((ram_mb / 5))
# Create the swap file
echo "Creating swap file of size $((swap_mb / 1024)) GB..."
${SUDO} dd if=/dev/zero of=/swapfile bs=1M count=$swap_mb
${SUDO} chmod 0600 /swapfile
# Format the swap file
${SUDO} mkswap /swapfile
# Enable the swap file
${SUDO} swapon /swapfile
# Comment out old swap config from fstab
${SUDO} sed -i '/swap/s/^/#/' /etc/fstab
# Add the new swap file entry to /etc/fstab
echo "/swapfile none swap sw 0 0" | ${SUDO} tee -a /etc/fstab
# Do not add sysctl config if it exists
if grep -q 'vm.swappiness' /etc/sysctl.conf; then
echo "Sysctl config for swap already exists, skipping..."
else
echo 'vm.swappiness = 10' | ${SUDO} tee -a /etc/sysctl.conf
fi
if grep -q 'fs.inotify.max_user_watches' /etc/sysctl.conf; then
echo "Sysctl config for swap already exists, skipping..."
else
echo 'fs.inotify.max_user_watches = 524288' | ${SUDO} tee -a /etc/sysctl.conf
fi
# Echo success message
echo "Swap file created and enabled successfully!"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment