Skip to content

Instantly share code, notes, and snippets.

@bouroo
Last active July 8, 2025 08:51
Show Gist options
  • 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 <[email protected]>
# usage: bash swap.sh
# notes: need `sudo dd sed` packages
#==============================================================================
# Exit immediately if a command exits with a non-zero status.
# Treat unset variables as an error when substituting.
# The exit status of a pipeline is the exit status of the last command that exited with a non-zero status,
# or zero if all commands in the pipeline exit successfully.
set -euo pipefail
# Determine if sudo is needed
SUDO=""
if [ "$(whoami)" != "root" ]; then
if command -v sudo &>/dev/null; then
SUDO="sudo"
else
echo "Error: This script requires root privileges or the 'sudo' command." >&2
exit 1
fi
fi
# Define constants
SWAP_FILE="/swapfile"
MIN_SWAP_MB=1024 # Minimum swap size in MB (1GB)
# Function to add or update a sysctl parameter
add_sysctl_param() {
local param="$1"
local value="$2"
local description="$3"
if grep -q "^${param}" /etc/sysctl.conf; then
echo "Sysctl config for '${param}' already exists, skipping addition."
else
echo "${param} = ${value}" | ${SUDO} tee -a /etc/sysctl.conf >/dev/null
echo "Added sysctl config: ${param} = ${value} (${description})"
fi
}
echo "Starting swap file creation process..."
# Check and disable existing swap devices
if swapon -s | grep -q '/'; then
echo "Existing swap devices detected. Disabling them now..."
${SUDO} swapoff -a
else
echo "No active swap devices found. Proceeding..."
fi
# Get the amount of RAM in MB
ram_mb=$(free -m | awk '/Mem:/ {print $2}')
echo "Detected RAM: ${ram_mb} MB"
# Calculate the swap size in MB (20% of RAM), ensuring a minimum size
swap_mb=$((ram_mb / 5))
if [ "${swap_mb}" -lt "${MIN_SWAP_MB}" ]; then
swap_mb="${MIN_SWAP_MB}"
echo "Calculated swap size is less than ${MIN_SWAP_MB}MB. Setting to ${MIN_SWAP_MB}MB."
fi
echo "Calculated swap size: ${swap_mb} MB ($((swap_mb / 1024)) GB)"
# Create the swap file
echo "Creating swap file at ${SWAP_FILE}..."
${SUDO} dd if=/dev/zero of="${SWAP_FILE}" bs=1M count="${swap_mb}" status=none
${SUDO} chmod 0600 "${SWAP_FILE}"
echo "Swap file created and permissions set."
# Format the swap file
echo "Formatting ${SWAP_FILE} as swap..."
${SUDO} mkswap "${SWAP_FILE}"
# Enable the swap file
echo "Enabling the new swap file..."
${SUDO} swapon "${SWAP_FILE}"
# Comment out old swap config from fstab
echo "Commenting out old swap entries in /etc/fstab..."
# This sed command comments out any line containing the word 'swap'.
${SUDO} sed -i '/swap/s/^/#/' /etc/fstab
# Add the new swap file entry to /etc/fstab
echo "Adding new swap file entry to /etc/fstab..."
echo "${SWAP_FILE} none swap sw 0 0" | ${SUDO} tee -a /etc/fstab >/dev/null
# Configure sysctl parameters for swap and inotify
echo "Configuring sysctl parameters..."
add_sysctl_param "vm.swappiness" "10" "Controls how often the system swaps"
add_sysctl_param "fs.inotify.max_user_watches" "524288" "Increases max watches for inotify (e.g., for IDEs)"
# Apply sysctl changes
echo "Applying sysctl changes..."
${SUDO} sysctl -p
echo "Swap file created and enabled successfully!"
echo "Current swap status:"
free -h
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment