Skip to content

Instantly share code, notes, and snippets.

@ilovefreesw
Created November 14, 2024 11:15
Show Gist options
  • Save ilovefreesw/c5b31f3818f1ba162f33ea306cbe4fce to your computer and use it in GitHub Desktop.
Save ilovefreesw/c5b31f3818f1ba162f33ea306cbe4fce to your computer and use it in GitHub Desktop.
A bash script to create a swap space on a server in one go. Takes swap size and swappiness value as input parameters. Run it as root.
#!/bin/bash
# Prompt the user for swap size and swappiness
read -p "Enter the swap size (e.g., 4G, 2G): " swap_size
read -p "Enter the swappiness value (0-100): " swappiness
# Create the swap file with the specified size
fallocate -l "$swap_size" /swapfile
# Set permissions on the swap file
chmod 600 /swapfile
# Setup the swap area
mkswap /swapfile
# Enable the swap file
swapon /swapfile
# Backup the fstab file
cp /etc/fstab /etc/fstab.bak
# Add the swap entry to fstab to make it permanent
echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
# Set the swappiness value
sysctl vm.swappiness="$swappiness"
# Update sysctl.conf with the new swappiness setting
if grep -q "vm.swappiness" /etc/sysctl.conf; then
# Update existing swappiness setting
sed -i "s/^vm.swappiness=.*/vm.swappiness=$swappiness/" /etc/sysctl.conf
else
# Add swappiness setting if not present
echo "vm.swappiness=$swappiness" >> /etc/sysctl.conf
fi
echo "Swap space of $swap_size created with swappiness set to $swappiness."
@ilovefreesw
Copy link
Author

Explanation:

  1. Inputs: The script prompts the user to enter the swap size (e.g., 4G) and swappiness value (e.g., 10).
  2. Swap Creation: Uses fallocate to create the swap file, configures it, and enables it.
  3. Persistence: Adds the swap configuration to /etc/fstab to ensure it remains active after reboot.
  4. Swappiness Configuration: Sets the immediate swappiness value using sysctl and also adds it to /etc/sysctl.conf for persistence across reboots.

Run this script as the root user to avoid needing sudo for each command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment