Created
November 14, 2024 11:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
4G
) and swappiness value (e.g.,10
).fallocate
to create the swap file, configures it, and enables it./etc/fstab
to ensure it remains active after reboot.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.